【问题标题】:Check if datagridview cell is null or empty [duplicate]检查datagridview单元格是否为空或为空[重复]
【发布时间】:2015-03-31 21:53:26
【问题描述】:

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

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

数据集已完成,显示填充的 datagridview 并显示此错误:

我该如何解决这个问题?有其他方法写代码吗?

【问题讨论】:

  • 如果 DGV 是 AllowUserToAddRows = True 那么你迭代的一行太多了。涵盖在 NRE 答案中
  • 使用debug,如果之后有问题,还有如何解决NullReferenceException的问题。

标签: c# visual-studio datagridview


【解决方案1】:

我会使用类似以下的方式遍历单元格..

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

【讨论】:

    【解决方案2】:

    您不需要ToString()。见here.

    下面的代码就足够了。

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

    你也可以试试:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-20
      • 2010-11-01
      • 2020-07-28
      相关资源
      最近更新 更多