2012-03-05 55 views
0

如何检查C#中的DataGridView中的空单元格值?我用DBNull来检查,但它不工作,我得到“对象引用未设置为对象的实例”错误。 我正在使用VS2010。DataGridView中的空值

任何人都可以帮助我吗?

DateGridView具有以下属性: 名称:dgTelFax AllowUserToAddRows:真 AllowUserToDeleteRows:真

的代码我目前拥有的是:提前

  DataSet objDSTelephone = new DataSet(); 
      DataTable objDTTelephone = objDSTelephone.Tables.Add(); 

      string strTelephoneID = ""; 
      string strTelephone = ""; 

      int intRecTel = dgTelFax.Rows.Count; 
      if (intRecTel > 0) 
      { 
       //-- Add columns to the data table 
       objDTTelephone.Columns.Add("id", typeof(string)); 
       objDTTelephone.Columns.Add("telephone", typeof(string)); 

       for (int i2 = 0; i2 <= intRecTel - 1; i2++) 
       { 
        strTelephoneID = (!DBNull.Value.Equals(dgTelFax.Rows[i2].Cells[0].Value)) ? dgTelFax.Rows[i2].Cells[0].Value.ToString() : ""; 
        strTelephone = (!DBNull.Value.Equals(dgTelFax.Rows[i2].Cells[2].Value)) ? dgTelFax.Rows[i2].Cells[2].Value.ToString() : ""; 
        objDTTelephone.Rows.Add(strTelephoneID, strTelephone); 
       } 
      } 

谢谢!

+0

检查了这一点http://stackoverflow.com/questions/3155684/handle-empty-cells-in-datagridview – Raymund 2012-03-05 00:59:45

回答

1

在这种情况下,您的dgTelFax不包含DBNull.Value,而是包含简单的null。为了验证这一点,你可以这样写:

strTelephoneID = (dgTelFax.Rows[i2].Cells[0].Value ?? string.Empty).ToString(); 
strTelephone = (dgTelFax.Rows[i2].Cells[2].Value ?? string.Empty).ToString(); 

如果数据源列的类型为字符串,就足以说:

strTelephoneID = (string)dgTelFax.Rows[i2].Cells[0].Value; 
strTelephone = (string)dgTelFax.Rows[i2].Cells[2].Value; 

但问题是 - 你为什么不绑定到数据网格objDTTelephone?那么你不需要自己传输数据。

0

获得Cell值前检查电池值:

if(!string.IsNullOrEmpty(dgTelFax.Rows[2].Cells[0].Value) { 
    strTelephoneID = dgTelFax.Rows[2].Cells[0].Value.Tostring(); 
}