1

In my database I have 6 columns, all of them allow null values. I want to make a simple form with an updating feature.

Product , SNO ,BTCH Expiry ,QTY ,RATE and Amount.

I get an exception:

Unable to cast object of type 'System.DBNull' to type 'System.String'

Here is my code :

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;
            }
Mat
  • 202,337
  • 40
  • 393
  • 406
ebbicsku
  • 51
  • 1
  • 1
  • 7

3 Answers3

5

Try this

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

or

lblSNO.Text = (erow.SNO == DBNull.Value) ? string.Empty : erow.SNO.ToString() 
Blachshma
  • 17,097
  • 4
  • 58
  • 72
3

Have a look at this similar example for handling DBNulls

Community
  • 1
  • 1
Ebad Masood
  • 2,389
  • 28
  • 46
2

Before calling ToString method call Convert.IsDBNull to check if value is not null.

Marek Dzikiewicz
  • 2,844
  • 1
  • 22
  • 24