检查datagridview的单元格中的数据是否为空

时间:2012-02-20 12:53:12

标签: c# .net sql ado.net datagridview

我的DataGridView通过SqlDataReader绑定到数据库查询结果,当我测试null的单元格值时,我得到了意外的结果。

我的代码是这样的:

SqlConnection con = new SqlConnection(
     "Data Source = .;Initial Catalog = SAHS;integrated security = true");
con.Open();
SqlCommand cmd3 = new SqlCommand(
    "select  Status from vw_stdtfeedetail 
     where Std= 6  and Div ='B' and name='bbkk' and mnthname ='June'", con);
SqlDataReader dr = cmd3.ExecuteReader();
BindingSource bs = new BindingSource();
bs.DataSource = dr;
dataGridView3.DataSource = bs;
this.monthFeeTableAdapter.Fill(this.sAHSDataSet4.MonthFee);
if (dataGridView3.CurrentCell.Value == null)
{
    MessageBox.Show("Pending");
}
else
{
    MessageBox.Show("Already Paid");
}

即使数据库中的值为 null ,我的输出已经付费

1 个答案:

答案 0 :(得分:4)

尝试使用DBNull.Value代替null

if (dataGridView3.CurrentCell.Value == DBNull.Value)
{
    MessageBox.Show("Pending");
}
else
{
    MessageBox.Show("Already Paid");
}