C# C遍历dataGridView以查找空值,并改为放置“0”

C# C遍历dataGridView以查找空值,并改为放置“0”,c#,datagridview,null,C#,Datagridview,Null,我希望遍历dataGridView中找到的所有值,检查该值是否为null,如果为null,则放置一个0值,使其不为null。你能帮忙吗 for (int i = 0; i < (dataGridView1.Rows.Count - 1); i++) { for (int j = 0; j < (dataGridView1.Columns.Count - 1); j++) { if (dataGridView1.Rows[i].Cells[j].Valu

我希望遍历dataGridView中找到的所有值,检查该值是否为null,如果为null,则放置一个0值,使其不为null。你能帮忙吗

for (int i = 0; i < (dataGridView1.Rows.Count - 1); i++)
{
    for (int j = 0; j < (dataGridView1.Columns.Count - 1); j++)
    {
        if (dataGridView1.Rows[i].Cells[j].Value == null)
        {
            dataGridView1.Rows[i].Cells[j].Value.Equals("0");
        }
    }
}

谢谢

有两种方法可以显示0而不是null或空值:

第一个是在将数据源绑定到DataGrid之前更新数据源

第二个是使用下面的代码

foreach(DataGridViewRow row in dataGridView1.Rows)
            foreach(DataGridViewCell cell in row.Cells)
            {
                if(cell.Value == null ||  cell.Value.ToString() == string.Empty)
                {
                    cell.Value = "0";
                }
            }
使用:

作为检查DataGridView中空值的条件。如果需要,还可以检查String.IsNullOrWhitespace。

尝试以下操作:

 foreach (DataGridViewRow row in dataGridView1.Rows)
 {
      foreach (DataGridViewCell item in row.Cells)
      {
           if(item.Value == null || item.Value == DBNull.Value || String.IsNullOrWhiteSpace(item.Value.ToString()))
           {
               item.Value = "0";
           }
      }              
}

如果您使用的是mssql,则可以在绑定到网格之前检查查询中列的值

SELECT ISNULL(column_name, 0)  from table_name
返回与check_表达式相同的类型。如果提供了文本NULL作为check_表达式,则返回替换_值的数据类型。如果提供了文本NULL作为check_表达式,并且没有提供替换_值,则返回int

第一个解决方案: 若您从数据库中检索数据,那个么在database end中将null值替换为0,请像这样使用Isnull函数 从表中选择Isnullcolumnname,0 第二种解决方案: 使用GridView.RowDataBound事件 void GridView_RowDataBoundObject发送方,GridViewRowEventArgs e { ife.Row.RowType==DataControlRowType.DataRow { ife.Row.Cells[使用单元格id].Text==null { e、 Row.Cells[使用单元格id].Text=0; } }
}

您的代码有什么问题?你所缺少的只是需要检查另外两个条件。Value.ToString==并且可能Value==DBNull.Value
SELECT ISNULL(column_name, 0)  from table_name