C#遍历dataGridView查找空值并放置“0”代替

C# Traverse dataGridView to find null value and place "0" instead

我想遍历dataGridView中找到的所有值,检查该值是否为空,如果为空则放置一个“0”值,这样它就不会为空。你能帮忙吗?

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 或空值:

第一个 正在更新 DataSource,然后再将其绑定到 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";
                }
            }

使用:

if (dataGridView1.Rows[i].Cells[j].Value == System.DBNull.Value)
{
    dataGridView1.Rows[i].Cells[j].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

Returns 与 check_expression 类型相同。如果作为 check_expression 提供文字 NULL,returns replacement_value 的数据类型。如果以 check_expression 形式提供文字 NULL 且未提供 replacement_value,则 returns 为 int.

https://msdn.microsoft.com/en-us/library/ms184325.aspx

第一个解:
如果您从数据库中检索数据然后在数据库端将空值替换为 0,请像这样使用 Isnull 函数
select 来自 table
的 Isnull(列名,0) 第二个解决方案:
使用GridView.RowDataBound事件
void GridView_RowDataBound(对象发送者, GridViewRowEventArgs e)
{
如果(e.Row.RowType == DataControlRowType.DataRow)
{
如果(e.Row.Cells["use cell id"].Text == null)
{
e.Row.Cells["use cell id"].Text = "0";
}
}
}