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

c#, gridview

Solution

Try this

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

or

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

Problem

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

Original source

Related problems