0

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.

Fergie35
  • 3
  • 2
  • 1
    The following post has examples that show how to `IsDbNull()` to gracefully deal with the situation you have: https://stackoverflow.com/questions/5409936/casting-datareader-value-to-a-to-a-nullable-variable – David Tansey Mar 14 '21 at 21:35
  • 1
    @DavidTansey that's really useful thank you. – Fergie35 Mar 14 '21 at 22:42
  • Further issues with your code: 1. **Use parameters, do NOT concatenate/interpolate query values** or you leave yourself open to SQL injection 2. Dispose connection, command and reader in `using` blocks 3. Avoid `select *`, specify the columns you need 4. Do not block waiting for the user or IO while the connection is open – Charlieface Mar 14 '21 at 23:14
  • @Fergie35 Welcome to StackOverflow #SOReadyToHelp – David Tansey Mar 15 '21 at 02:33

1 Answers1

1

One of this columns is null. So you have to use reader like this:

if ( reader["Model"] != DBNull.Value) tbModel.Text = reader["Model"].ToString();

Serge
  • 40,935
  • 4
  • 18
  • 45