Skip to main content
 首页 » 编程设计

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

2024年02月23日1498°冷暖

我的 DataGridView 通过 SqlDataReader 绑定(bind)到数据库查询结果,当我测试 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,我也得到了输出Already Paid。

请您参考如下方法:

尝试使用 DBNull.Value 而不是 null

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