Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/265.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 检查datagridview单元格是否为null或空_C#_Visual Studio_Datagridview - Fatal编程技术网

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

C# 检查datagridview单元格是否为null或空,c#,visual-studio,datagridview,C#,Visual Studio,Datagridview,我必须更改单元格的背景色,当它们的值为字符串或空时,这是我编写的代码,类似于此处的其他代码: for (int rowIndex = 0; rowIndex < dataGridView1.RowCount; rowIndex++) { string conte = dataGridView1.Rows[rowIndex].Cells[7].Value.ToString() ; if (string.IsN

我必须更改单元格的背景色,当它们的值为字符串或空时,这是我编写的代码,类似于此处的其他代码:

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; }
        } 
for(int-rowIndex=0;rowIndex
数据集已完成,请显示已填充的datagridview,并显示此错误:


我怎样才能解决这个问题??有其他方法来编写代码吗?

我将使用如下内容遍历单元格

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;       
    }
}

您不需要
ToString()
。看

下面的代码就足够了

string conte = dataGridView1.Rows[rowIndex].Cells[7].Value;
您也可以尝试以下方式:

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

如果DGV为AllowUserToAddress=True,则迭代一行的次数过多。在NRE answeruse调试中介绍,如果您在调试之后遇到问题,则会有如何解决NullReferenceException的问题。