2016-04-24 141 views
2

我已尝试使用此代码,但它对我无效。如何更改行基于单元格值的背景颜色

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

+0

你是什么意思_does不work_完全?你得到任何异常或错误信息?你可以请更具体吗? –

+0

是的,它说,对象不能从DBNULL转换为其他类型。 和我应该使用哪个事件代码? –

回答

1

我认为的条件的顺序是有问题的。您首先尝试将该值转换为两倍。 然后您检查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转换为其他类型。

+0

非常感谢,它的作品! –

0

作为补充,如果此列BoundField,你可以设置它的NullDisplayText property,以及当你在该列DBNull的值,显示其价值。

相关问题