如何更改行基于单元格值的背景颜色
问题描述:
我已尝试使用此代码,但它对我无效。如何更改行基于单元格值的背景颜色
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;
}
}
答
我认为的条件的顺序是有问题的。您首先尝试将该值转换为两倍。 然后您检查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
非常感谢,它的作品! –
你是什么意思_does不work_完全?你得到任何异常或错误信息?你可以请更具体吗? –
是的,它说,对象不能从DBNULL转换为其他类型。 和我应该使用哪个事件代码? –