0

Long story short, I have to send data from a C# Form to SQL but I keep getting a Null reference in this line:

adapter.InsertCommand.Parameters["@genre"].Value = textBox1.Text;

I get the error when I click the button to send the data to the database. It also says:

Reference to an object not set"...

I tried a few things to fix it but I can't seem to figure out where is the null value. Here's the full code for that form. Keep in mind that I have more forms on the same project if that's of any relevance:

public partial class Form4 : Form
{
    public Form4()
    {
        InitializeComponent();
    }

    private SqlConnection connection;
    private SqlDataAdapter adapter;

    private void Form2_Load(object sender, EventArgs e)
    {
        connection = new SqlConnection("Data Source=USER;Initial Catalog=administracion;Integrated Security=True");         
        adapter = new SqlDataAdapter();
        SqlCommand save = new SqlCommand("insert into genres (genre, genre_description)"+
        "values (@genre, @genre_description)", connection);
        adapter.InsertCommand = save;   
        adapter.InsertCommand.Parameters.Add(new SqlParameter("@genre", SqlDbType.VarChar));
        adapter.InsertCommand.Parameters.Add(new SqlParameter("@genre_description", SqlDbType.VarChar));
    }

    private void textBox_TextChanged(object sender, EventArgs e)
    {
        textBox1.MaxLength = 50;
        textBox2.MaxLength = 200;
    }

    private void button1_Click(object sender, EventArgs e)
    {
        adapter.InsertCommand.Parameters["@genre"].Value = textBox1.Text; // on this line I get the null reference exception
        adapter.InsertCommand.Parameters["@genre_description"].Value = textBox2.Text;

        try         
        {             
            connection.Open();             
            adapter.InsertCommand.ExecuteNonQuery();
            MessageBox.Show("Genre added to database", "Data Saved", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }
        catch (SqlException exception) 
        { 
            MessageBox.Show(exception.ToString()); 
        }
        finally 
        { 
            connection.Close(); 
        }   
    }
}

I'm a newbie at this particular programming language, so I want to apologize if it's a pretty basic question (which probably is)

10
  • If you place a breakpoint at the line, which object is null? Commented Nov 11, 2014 at 20:46
  • 1
    possible duplicate of What is a NullReferenceException and how do I fix it? Commented Nov 11, 2014 at 20:46
  • Not sure if this would be causing it, but you are missing a space in "insert into genres (genre, genre_description)" + "values (@genre, @genre_description)" between "genre_description)" and "values" Commented Nov 11, 2014 at 20:46
  • 2 possible things: adapter is not getting initialized, or textBox1 isn't. Can you guarantee that Form2_Load is called before button1_click can be initiated by the user? Put a breakpoint at the line that's throwing the exception and see what the values are for adapter and textBox1 Commented Nov 11, 2014 at 20:47
  • 1
    you're in Form4 but have a method Form2_Load that's doing your initialization. Is it getting called? Commented Nov 11, 2014 at 20:48

1 Answer 1

2

Looking at the code, I suspect you haven't hooked up the load event; since that load event handler is creating your SQL connection, insert command, etc, they are null since it isn't called and you're accessing them in your button click event handler.

To prove that theory change this:

public Form4()
{
    InitializeComponent();
}

to this:

public Form4()
{
    InitializeComponent();
    this.Load += Form4_Load;
    this.Closed += Form4_Closed;
}

Add this:

void Form4_Closed(object sender, EventArgs e)
{
    this.Load -= Form4_Load;
    this.Closed -= Form4_Closed;
}

and change this

private void Form2_Load(object sender, EventArgs e)

to this

private void Form4_Load(object sender, EventArgs e)

since your form is named Form4, not Form2 (I assume you copied this out of another form in your project?).

Sign up to request clarification or add additional context in comments.

3 Comments

you assumed right, I copied it from another class of the same project to save some time, and I didn't realize the screw up. It's working perefctly now. Thank you so much for the help!!
The event handler add / remove code (+= / -=) is inside the InitializeComponent() method if you do it via the Visual Studio UI so it can be tricky to track down sometimes.
yeah, I was going nuts trying to find out what the hell was wrong with the code, mainly because I don't have that much experience with C# (as you can probably tell by now), and I had a hard time with that issue before, so I guess I should pay more attention to these kind of things from now on. Anyway, thanks for the time and the answers man! It really helped a lot!!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.