c#
DataGridView 根据列数据,依条件设置单元格Cell颜色
用例:DataGridView中有一列用来显示学生成绩,分数>60,设置单元格(Cell)背景黄色,字体蓝色,分数<60,单元格(Cell)背景红色,字体白色
效果图
实现方法
注册CellFormatting事件
this.dataGridView1.CellFormatting += DataGridView1_CellFormatting;
// 注册**CellFormatting**事件
this.dataGridView1.CellFormatting += DataGridView1_CellFormatting;
private void DataGridView1_CellFormatting(object? sender, DataGridViewCellFormattingEventArgs e)
{
if (e.RowIndex >= 0 && e.ColumnIndex >= 0 && e.RowIndex <= this.dataGridView1.Rows.Count)
{
//如果是Score列
//分数>60 背景黄色,字体颜色蓝色
//分数<60 背景红色,字体颜色白色
if (this.dataGridView1.Columns[e.ColumnIndex].Name=="Score")
{
int score = Convert.ToInt32(e.Value);
if (score > 60)
{
e.CellStyle.BackColor = Color.Yellow;
e.CellStyle.ForeColor = Color.Blue;
}else
{
e.CellStyle.BackColor = Color.Red;
e.CellStyle.ForeColor = Color.Wheat;
}
}
}
}