我试过这段代码,但它对我不起作用。
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;
}
}
最佳答案
我觉得条件顺序有问题。您首先尝试将值转换为 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: Object cannot be cast from DBNull to other types.
关于c# - 如何根据单元格值更改行背景颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36825100/