I have the following code I have written to access my database (SQL) and display values from it to textboxes on my WinForm. However I'm having problems when the database value being read is a null value. How do I go about handling it correctly so I don't get the following error, when I press the button that triggers the following code:
Error
Unable to cast object or type 'System.DBnNull' to type 'Sytem.String'
Code:
//Set stock number as the lookup
int stocknumber = int.Parse(tbStockNumber.Text);
//Database Connection
SqlConnection conn = new SqlConnection(myconnstrng);
SqlCommand command = new SqlCommand("SELECT * FROM Wholegoods_History WHERE Stock_Number = " + stocknumber + " ", conn);
try
{
conn.Open();
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
//Enter data into textboxes
tbModel.Text = (string)reader["Model"];
cmbBrand.Text = (string)reader["Brand"];
tbDescription.Text = (string)reader["Description"];
}
reader.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
conn.Close();
I assume I will have the same problem back the other way when a textbox is empty and I try to save a record to the database or update one.