Search code examples
c#sql-servervisual-studiowinformsnullreferenceexception

Get data from SQL table throwing null exception even when try block is present


In my WinForms app I have this below code which fetches the lot number from a SQL Server table when the button is clicked.

private void getlotnumbers()
{
    try
    {
        SqlConnection con = new SqlConnection(cs);
        SqlCommand cmd;
        con.Open();
        string s = "select LotNumber from Lot_Numbers where CoilNumber = @p1";
        cmd = new SqlCommand(s, con);
        cmd.Parameters.AddWithValue("@p1", coilNoTextBox.Text);
        cmd.CommandType = CommandType.Text;
        int i = cmd.ExecuteNonQuery();
        lotNoTextBox.Text = cmd.ExecuteScalar().ToString();
        con.Close();
    }
    catch(Exception ex)
    {
        MessageBox.Show("Lot Number Not Found:" + ex.Message.ToString(), "Lot Number",
            MessageBoxButtons.OK, MessageBoxIcon.Error);
    }        
}

The function was working fine till yesterday, but from today it is throwing below exception and stopping the application even though try block is present.

System.NullReferenceException: 'Object reference not set to an instance of an object.'

I don't know why is this happening, but I was adding another form called "formedit" to edit the existing record, which is very similar to "FornewEntry", but with prefilled values of selected datagridview row, maybe I have messed up something while doing the same as this is first application as I am learning C# below is the link to my solution kindly help me.


Solution

  • you are trying to execute this statement string s = "select LotNumber from Lot_Numbers where CoilNumber = @p1"; I think your lotNumber column value is null and when you execute lotNoTextBox.Text = cmd.ExecuteScalar().ToString(); it will return null so if you can handle it

    var lotNumber= cmd.ExecuteScalar()==null?"Handle empty case or throw exception with custom message":cmd.ExecuteScalar().ToString();
    lotNoTextBox.Text =lotNumber.ToString();