C# DataGridView中的空值

C# DataGridView中的空值,c#,winforms,C#,Winforms,如何在C#中检查DataGridView中的空单元格值?我已经使用DBNull进行检查,但它不起作用,并且出现了“对象引用未设置为对象实例”错误。 我正在使用VS2010 有人能帮我吗 DateGridView具有以下属性: 姓名:dgTelFax AllowUserToAddress:正确 AllowUserToDeleteRows:正确 我目前拥有的代码是: DataSet objDSTelephone = new DataSet(); Dat

如何在C#中检查DataGridView中的空单元格值?我已经使用DBNull进行检查,但它不起作用,并且出现了“对象引用未设置为对象实例”错误。 我正在使用VS2010

有人能帮我吗

DateGridView具有以下属性: 姓名:dgTelFax AllowUserToAddress:正确 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);
                }
            }
DataSet objDSTelephone=新数据集();
DataTable objdtelephone=objDSTelephone.Tables.Add();
字符串strTelephoneID=“”;
字符串strTelephone=“”;
int intRecTel=dgTelFax.Rows.Count;
如果(整数>0)
{
//--向数据表中添加列
objdtelephone.Columns.Add(“id”,typeof(string));
objdtelephone.Columns.Add(“电话”,typeof(字符串));

对于(int i2=0;i2在本例中,您的dgTelFax不包含DBNull.Value,而是简单的null。要测试这一点,您可以编写:

strTelephoneID = (dgTelFax.Rows[i2].Cells[0].Value ?? string.Empty).ToString();
strTelephone = (dgTelFax.Rows[i2].Cells[2].Value ?? string.Empty).ToString();
如果DataSource中的列类型为string,则可以说:

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

但问题是-为什么不将datagrid绑定到objDTTelephone?这样您就不需要自己传输数据了。

在获取单元格值之前,请检查单元格值:

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