2012-05-17 66 views
0

在我的数据库中,我有6列,它们都允许空值。 I 想要制作具有更新功能的简单表单。无法转换System.DBNull类型的对象来输入System.String

产品,SNO,BTCH到期,数量,费率和金额。

我得到一个异常:

无法转换类型为 'System.DBNull' 的对象为类型 'System.String'

这里是我的代码:

int a = dataGridView1.CurrentCell.RowIndex; 

      try 
      { 

       using (AmdDataSet.Test_ibrahimDataTable table = new AmdDataSet.Test_ibrahimDataTable()) 
       { 

        int b = a+1; 
        using (AmdDataSetTableAdapters.Test_ibrahimTableAdapter adp = new AmdDataSetTableAdapters.Test_ibrahimTableAdapter()) 
        { 
         adp.GetDataBySNO(a); 
         AmdDataSet.Test_ibrahimRow erow; 
         erow = table.NewTest_ibrahimRow(); 
         lblSNO.Text = erow.SNO.ToString(); 
         txtProduct.Text= erow.PRODUCTS; 
         txtExpiry.Text = erow.EXPIRYDATE.ToShortDateString(); 
         txtBatchNo.Text = erow.BATCHNO.Trim().ToString(); 

        } 
       } 
      } 
      catch (Exception ex) 
      { 
       lbleror.Text = ex.Message; 
      } 

回答

4

试一下这个

lblSNO.Text = (erow.SNO == null) ? string.Empty : erow.SNO.ToString() 

lblSNO.Text = (erow.SNO == DBNull.Value) ? string.Empty : erow.SNO.ToString() 
+1

其实第二个选项将工作 –

+0

lblSNO.Text =(erow.SNO == DBNull.Value) ? string.Empty:erow.SNO.ToString()它显示不能应用类型int – ebbicsku

+0

数据库中SNO列的类型是什么? – Blachshma

2

在致电ToString方法调用Convert.IsDBNull以检查值是否不为空。

相关问题