Object reference error

Muhammad Adeel 20 Reputation points
2023-12-17T08:15:18.7433333+00:00

        int CId = 0;
        

        private void button1_Click(object sender, EventArgs e)
        { 
            try
            {
                if (textBox1.Text == "" || textBox2.Text == "" || comboBox1.SelectedIndex == -1 || textBox3.Text == "")
                {
                    MessageBox.Show("Missing information");
                }
                else
                {
                    Con.Open();
                    SqlCommand cmd = new SqlCommand("INSERT INTO EventTbl(CName,CPhone,Events,Date) VALUES (@CN, @CP, @E, @D)",Con);
                    cmd.Parameters.AddWithValue("@CN", textBox1.Text);
                    cmd.Parameters.AddWithValue("@CP", textBox2.Text);
                    cmd.Parameters.AddWithValue("@E", comboBox1.SelectedValue.ToString());
                    cmd.Parameters.AddWithValue("@D", textBox3.Text);
                    cmd.BeginExecuteNonQuery();
                    Con.Close();
                    MessageBox.Show("Record Entered Sucessfully");
                    DisplayEvent();

                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            finally { Con.Close(); }
        }
What error is found is this code i have an eoor of object reference is not set to an instance of an object
Windows 11
Windows 11
A Microsoft operating system designed for productivity, creativity, and ease of use.
11,159 questions
0 comments No comments
{count} votes

Accepted answer
  1. Q&A Assist
    2023-12-17T08:15:18.75+00:00
    AI generated content. This question contains an answer created with AI from Q&A Assist. Learn more

    The error "object reference is not set to an instance of an object" occurs when you try to use an object that has not been initialized. In the provided code, it is possible that the Con object has not been initialized before it is used in the try block. To resolve this error, you should initialize the Con object before using it.


    References:

    0 comments No comments

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.