如何在DataGridView中动态修改指定单元格颜色,现有代码失效如何解决
问题原因及修改方案
你写的颜色设置逻辑不生效核心有3个问题:
- 颜色判断逻辑嵌套在XML节点遍历的循环内,如果对应行ID在XML中没有匹配到
<item>节点,所有颜色设置代码都不会执行,而你本身已经直接从行的第7列取到了barhesap的值,不需要依赖XML节点遍历 - 没有过滤空白新增行、空值行,遇到空值会抛出隐式异常导致逻辑中断
- 代码执行时机不对,大概率是在DataGridView数据加载完成前就执行了样式设置,后续数据加载覆盖了之前的样式配置
优化后的颜色设置代码
private void RefreshCellColor() { // XML加载提到循环外,避免每一行都重复读磁盘 XDocument x = XDocument.Load(@"../../Data/gemi1/gemi1s1.xml"); foreach (DataGridViewRow row in dataGridView1.Rows) { // 跳过新增空白行、空值行 if (row.IsNewRow || row.Cells[5].Value == null || row.Cells[7].Value == null) continue; int barhesap = Convert.ToInt32(row.Cells[7].Value); int cell5Val = Convert.ToInt32(row.Cells[5].Value); // 移除多余的XML节点遍历逻辑,直接判断设置样式 if (cell5Val <= barhesap / 10) { row.Cells[5].Style.BackColor = Color.Lime; row.Cells[5].Style.ForeColor = Color.Black; } else if (cell5Val <= barhesap / 8) { row.Cells[5].Style.BackColor = Color.Green; row.Cells[5].Style.ForeColor = Color.Black; } else if (cell5Val <= barhesap / 6) { row.Cells[5].Style.BackColor = Color.DarkGreen; row.Cells[5].Style.ForeColor = Color.Black; } else if (cell5Val <= barhesap / 4) { row.Cells[5].Style.BackColor = Color.Yellow; row.Cells[5].Style.ForeColor = Color.Black; } else if (cell5Val <= barhesap / 2) { row.Cells[5].Style.BackColor = Color.Orange; row.Cells[5].Style.ForeColor = Color.Black; } else if (cell5Val <= barhesap / 1.5) { row.Cells[5].Style.BackColor = Color.OrangeRed; row.Cells[5].Style.ForeColor = Color.Black; } else if (cell5Val <= barhesap / 1.2) { row.Cells[5].Style.BackColor = Color.DarkRed; row.Cells[5].Style.ForeColor = Color.White; } else if (cell5Val <= barhesap) { row.Cells[5].Style.BackColor = Color.Red; row.Cells[5].Style.ForeColor = Color.White; } } }
正确的调用时机
在你数据加载方法yukle()的最后一行调用RefreshCellColor()即可,每次新增、修改数据重新加载列表后都会自动刷新单元格颜色。如果需要每次数据绑定自动触发,可以给DataGridView绑定DataBindingComplete事件:
private void dataGridView1_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e) { RefreshCellColor(); }
内容的提问来源于stack exchange,提问作者Muhammed Sarıgül
相关产品推荐
相关产品推荐

