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的问题。