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

标签 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

最佳答案

我觉得条件顺序有问题。您首先尝试将值转换为 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/

相关文章:

c# - C# 4.0 中的方法重载与可选参数

c# - 使用 LINQ 仅基于单个对象属性获取两个对象列表之间的差异

c# - 用于从文件中读取不同数据类型和大小的超大字节数组的循环

java - 使用 apache poi (.xlsx) 的 excel 2007 无法读取内容

sql - 在 SQL (Athena) 中取消嵌套 : How to convert array of structs into an array of values plucked from the structs?

mysql - mysql 是自动递增下一个数字还是当前数字?

arrays - 从 [String]() 数组设置单元格 textLabel

c# - 查看 Properties.Settings.Default 变量

excel - 引用另一个工作表中的单元格,公式在 '+' 之后具有 '='

matlab - 如何以我想要的方式删除单元格中的空元素