2

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;
            }
0

2 Answers 2

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() 
Sign up to request clarification or add additional context in comments.

4 Comments

Actually the second option will work
lblSNO.Text = (erow.SNO == DBNull.Value) ? string.Empty : erow.SNO.ToString() it is Showing Cannot be applied of Type int
What is the type of SNO column in the DB?
These didn't work for me.. I had to use the Is[PropertyName]Null() method of the dataset property.
2

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.