DataGridView 根据列数据,依条件设置单元格Cell颜色

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;
                    }
                }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值