【问题标题】:Unable to cast object of type System.DBNull to type System.String [duplicate]无法将 System.DBNull 类型的对象转换为 System.String [重复]
【发布时间】:2012-05-24 19:10:59
【问题描述】:

在我的数据库中,我有 6 列,所有列都允许空值。一世 想要制作一个具有更新功能的简单表单。

产品、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;
            }

【问题讨论】:

    标签: c# gridview


    【解决方案1】:

    试试这个

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

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

    【讨论】:

    • 实际上第二个选项会起作用
    • lblSNO.Text = (erow.SNO == DBNull.Value) ? string.Empty : erow.SNO.ToString() 它显示不能应用 int 类型
    • DB中SNO列的类型是什么?
    • 这些对我不起作用。我不得不使用数据集属性的 Is[PropertyName]Null() 方法。
    【解决方案2】:
    【解决方案3】:

    在调用ToString方法之前调用Convert.IsDBNull检查值是否不为空。

    【讨论】:

      猜你喜欢
      • 2012-05-19
      • 2012-09-14
      • 2021-04-26
      • 1970-01-01
      相关资源
      最近更新 更多