相反的CellFormatting
,嘗試CellValueChanged
對於非綁定數據或DataBindingComplete
一個綁定的數據集。例如,假設你是「刪除/取消刪除」使用下面的Button.Click
事件中的一行:
private void Button1_Click(object sender, EventArgs e)
{
bool value = (bool)dataGridView1.CurrentRow.Cells["Deleted"].Value;
dataGridView1.CurrentRow.Cells["Deleted"].Value = !value;
// For bound data (like a DataTable) add the following line:
// ((DataTable)dataGridView1.DataSource).AcceptChanges();
}
綁定數據
更改行以這種方式「刪除」的列值將觸發以下事件處理器。因此,您可以用顏色的基礎上True
或False
該列的值的行:
private void DataGridView1_CellValueChanged(object sender, DataGridViewCellEventArgs e)
{
if (e.ColumnIndex == dataGridView1.Columns["Deleted"].Index)
{
dataGridView1.Rows[e.RowIndex].DefaultCellStyle.ForeColor = (bool)dataGridView1[e.ColumnIndex, e.RowIndex].Value ? Color.Red : Color.Black;
}
}
數據綁定
對於綁定數據,比如從DataTable
,處理DataBindingComplete
事件就足夠了。此事件將在綁定第一次設置以及更改後觸發 - 例如Button1.Click
事件的更改。在這裏,您將遍歷行並根據隱藏列的值設置所需的樣式。 (注意在Button1_Click
事件處理程序的附加變化對於具有DataTable
源網格這是需要給立即風格上的變化 - 否則它不會發生,直到您導航到不同的行)
private void DataGridView1_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
{
foreach (DataGridViewRow row in dataGridView1.Rows)
{
row.DefaultSCellStyle.ForeColor = (bool)row.Cells["Deleted"].Value ? Color.Red : Color.Black;
}
}
請發佈一個MCVE。預期結果的圖片也會有所幫助 – ASh