检查datagridview单元格是否为null或为空

5
我需要更改单元格的背景颜色,当它们的值为字符串或为空时。这是我写的代码,与此处的其他代码类似:
for (int rowIndex = 0; rowIndex < dataGridView1.RowCount; rowIndex++)
            {
             string conte = dataGridView1.Rows[rowIndex].Cells[7].Value.ToString()  ;
                if (string.IsNullOrEmpty(conte))
                {
                // dataGridView1.Rows[rowIndex].Cells[7].Style.BackColor = Color.Orange;
                }
                else
                 { dataGridView1.Rows[rowIndex].Cells[7].Style.BackColor = Color.Orange; }
        } 

数据集已经完整,展示给我填充的数据网格视图并且展示这个错误:enter image description here

如何解决这个问题?是否有其他编写代码的方式?


1
如果DGV的AllowUserToAddRows = True,则您会迭代多一行。在NRE答案中有涉及。 - Ňɏssa Pøngjǣrdenlarp
使用调试功能,如果在此之后出现问题,则有一个问题需要解决NullReferenceException。 - mybirthname
2个回答

7
我会像下面这样使用迭代方式遍历单元格..
foreach (DataGridViewRow dgRow in dataGridView1.Rows)
{
    var cell = dgRow.Cells[7];
    if (cell.Value != null)   //Check for null reference
    {
        cell.Style.BackColor = string.IsNullOrEmpty(cell.Value.ToString()) ? 
            Color.LightCyan :   
            Color.Orange;       
    }
}

3

您不需要使用ToString()方法。请参见此处

以下代码已足够。

string conte = dataGridView1.Rows[rowIndex].Cells[7].Value;

您也可以尝试类似以下的操作:

if (string.IsNullOrEmpty(dataGridView1.Rows[0].Cells[7].Value as string))

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接