get data from sql table throwing null exception even when try block is present

ravi kumar 331 Reputation points
2020-12-21T07:15:59.803+00:00

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 .

view

Windows Forms
Windows Forms
A set of .NET Framework managed libraries for developing graphical user interfaces.
1,903 questions
Visual Studio
Visual Studio
A family of Microsoft suites of integrated development tools for building applications for Windows, the web and mobile devices.
5,193 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
11,011 questions
0 comments No comments
{count} votes

Accepted answer
  1. Michael Taylor 54,811 Reputation points
    2020-12-21T16:26:42.137+00:00

    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.


0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.