如何在C#中根据字符串值设置DataGridView单元格颜色
解决DataGridView单元格颜色不生效的问题
以下是几个关键排查点和修正方案:
1. 确认事件已正确绑定
很多时候代码不生效是因为CellFormatting事件未与方法关联:
- 可视化操作:选中DataGridView,在属性窗口的「事件」面板中找到
CellFormatting,选择对应的DataGridView1_CellFormatting方法。 - 代码绑定:在窗体的
Load事件中添加:
private void Form_Load(object sender, EventArgs e) { dataGridView1.CellFormatting += DataGridView1_CellFormatting; }
2. 替换列判断逻辑(用ColumnName代替HeaderText)
HeaderText可能被界面修改,用数据源的ColumnName判断更可靠:
把原代码中的:
if (this.dataGridView1.Columns[e.ColumnIndex].HeaderText.Equals("over05"))
替换为:
if (dataGridView1.Columns[e.ColumnIndex].ColumnName == "over05")
3. 优化值处理逻辑,避免类型转换错误
直接强制转换e.Value为string可能出错,改用ToString()并做空值处理,同时用else if保证逻辑严谨:
修正后的完整代码:
private void DataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e) { if (dataGridView1.Columns[e.ColumnIndex].ColumnName == "over05") { string cellValue = e.Value?.ToString().Trim(); if (!string.IsNullOrEmpty(cellValue)) { if (cellValue == "OK") { e.CellStyle.BackColor = Color.Green; e.CellStyle.ForeColor = Color.White; // 可选,提升文字可读性 } else if (cellValue == "NO") { e.CellStyle.BackColor = Color.Red; e.CellStyle.ForeColor = Color.White; } // 标记格式已应用,防止默认样式覆盖 e.FormattingApplied = true; } } }
4. 额外排查点
- 检查数据源中该列的实际值:确保没有多余空格、大小写差异(比如
"ok"而非"OK"),如果需要忽略大小写,把判断改为cellValue.Equals("OK", StringComparison.OrdinalIgnoreCase)。 - 检查默认样式:如果DataGridView的行/列
DefaultCellStyle设置了背景色,可能会覆盖CellFormatting中的设置,需调整默认样式或确保CellFormatting的样式优先级更高。
内容的提问来源于stack exchange,提问作者Terra1
相关产品推荐
相关产品推荐

