如何根据单元格值更改行背景颜色

时间:2016-04-24 15:24:23

标签: c# row cell

我尝试过这段代码,但它对我不起作用。

for (int i = 0; i < GerezCmdsGridView.Rows.Count; i++)
{
    if (Convert.ToDouble(GerezCmdsGridView.Rows[i].Cells[7].Value) == 0 || GerezCmdsGridView.Rows[i].Cells[7].Value == DBNull.Value)
    {
        GerezCmdsGridView.Rows[i].DefaultCellStyle.BackColor = Color.Red;
    }            
}

enter image description here

2 个答案:

答案 0 :(得分:1)

我认为条件的顺序是有问题的。您首先尝试将值转换为double。 然后您检查DBNull.Value

所以你应该改变顺序:

if (GerezCmdsGridView.Rows[i].Cells[7].Value == DBNull.Value || 
    Convert.ToDouble(GerezCmdsGridView.Rows[i].Cells[7].Value) == 0)

如果您是第一次尝试转换dbnull(Convert.ToDouble(DBNull.Value)),则会引发异常:

  

System.InvalidCastException:无法将对象从DBNull强制转换为其他类型。

答案 1 :(得分:0)

另外,如果此列为BoundField,您可以设置NullDisplayText property以及当您在该列上获得DBNull值时显示的值。< / p>

相关问题