2015-07-21 200 views
1

我想遍歷在dataGridView中找到的所有值,檢查該值是否爲null,如果它爲null,則放置一個「0」值,以便它不會爲空。你能協助嗎?C#遍歷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

什麼是錯的代碼,你得到了什麼?你所缺少的是你需要檢查2個其他條件。 Value.ToString ==「」和可能的值== DBNull.Value – Equalsk

回答

1

用途:

if (dataGridView1.Rows[i].Cells[j].Value == System.DBNull.Value) 
{ 
    dataGridView1.Rows[i].Cells[j].Value="0"; 
} 

作爲在DataGridView中檢查空值的條件。如果您需要,您也可以檢查String.IsNullOrWhitespace

1

有2可以顯示「0」,而不是零值或空值的方法:

第一個正在更新綁定之前將DataSource它數據網格

第二個使用以下代碼

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

試試這個:

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

,如果你使用的是MSSQL,那麼你可以結合到電網之前在查詢中檢查列的值。

SELECT ISNULL(column_name, 0) from table_name 

返回與check_expression相同的類型。如果提供了作爲check_expression的文字NULL,則返回replacement_value的數據類型。如果提供的文字NULL作爲check_expression且不提供replacement_value,則返回int。

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

0

首個解決方案:
如果你從數據庫中檢索數據,則空值替換爲數據庫最終0,使用ISNULL函數這樣
選擇ISNULL(列名,0)從表
使用GridView.RowDataBound事件
void GridView_RowDataBound(Object sender,GridViewRowEventArgs e)
{
如果(e.Row.RowType == DataControlRowType.DataRow)
{
如果(e.Row.Cells [ 「使用小區ID」]。文本== NULL)
{
即Row.Cells [「use cell id」] .Text =「0」;
}
}
}