Set a breakpoint on line 6 and run your code. Then start stepping (F10) until the exception occurs. When it does you'll have found the line that is failing. The NullReferencException
indicates you have code that looks like this instance.member
and instance
is null. Looking at your code my gut instinct is that it is line 10 as that is the only object that isn't contained in the code you posted but stepping will tell you the exact line.
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 MSSQL 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 .
-
Michael Taylor 54,811 Reputation points
2020-12-21T16:26:42.137+00:00