摘要:資料符合特定條件時變更資料列(Row)的背景顏色
兩種方法
1. 修改 DataGridViewRow.DefaultCellStyle.BackColor
private void dataGridView1_RowPrePaint(object sender, DataGridViewRowPrePaintEventArgs e)
{
if (dataGridView1.Rows.Count <= e.RowIndex) return;
if (e.RowIndex < 0) return;
if (dataGridView1.Rows[e.RowIndex].Cells[1].Value == null) return;
if (dataGridView1.Rows[e.RowIndex].Cells[1].Value.ToString().ToUpper() == "TRUE")
{
DataGridViewRow row = dataGridView1.Rows[e.RowIndex];
row.DefaultCellStyle.BackColor = Color.SkyBlue;
if (row.Selected)
{
row.DefaultCellStyle.SelectionBackColor = Color.Yellow;
row.DefaultCellStyle.SelectionForeColor = Color.Red;
}
}
}
2. 修改 CellStyle.BackColor
private void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
if (dataGridView1.Rows.Count <= e.RowIndex) return;
if (e.RowIndex < 0) return;
if (dataGridView1.Rows[e.RowIndex].Cells[1].Value == null) return;
if (dataGridView1.Rows[e.RowIndex].Cells[1].Value.ToString().ToUpper() == "TRUE")
{
DataGridViewRow row = dataGridView1.Rows[e.RowIndex];
e.CellStyle.BackColor = Color.SkyBlue;
}
}
參考資料 MSDN DataGridViewRow.DefaultCellStyle屬性 及 DataGridView.CellFormatting事件