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)

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Danilo Bambi
  • 93
  • 1
  • 2
  • 10
  • If you place a breakpoint at the line, which object is null? – Ric .Net Nov 11 '14 at 20:46
  • 1
    possible duplicate of [What is a NullReferenceException and how do I fix it?](http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) – xxbbcc Nov 11 '14 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"` – Jacob Lambert Nov 11 '14 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` – Saggio Nov 11 '14 at 20:47
  • 1
    you're in `Form4` but have a method `Form2_Load` that's doing your initialization. Is it getting called? – Jonesopolis Nov 11 '14 at 20:48
  • @Jonesy Sorry for the delay in the answer, my internet is crap...Yes, there was a mistake in the load method, I already fixed it thanks to your suggestions... thank you so much for your time and your answers guys, they really helped a lot! – Danilo Bambi Nov 11 '14 at 21:28
  • @Saggio as said below by Allan Elder, the problem was that I didn't hook up the load event right after the InitializeComponent method, and also the "Form2_Load" line should have been "Form4_Load" instead. So yeah, it was a pretty dumb mistake to make. Anyway, thank you for taking the time to answer!! – Danilo Bambi Nov 11 '14 at 21:48
  • @JRLambert It wasn't that, but thanks for pointing that out, I didn't notice it. Thank you! – Danilo Bambi Nov 11 '14 at 21:51
  • @xxbbcc Thanks, that's going right to my bookmarks. – Danilo Bambi Nov 11 '14 at 21:53
  • @Ric .Net already solved it with Allan Elder's code, thank you so much for the time! – Danilo Bambi Nov 11 '14 at 21:55

1 Answers1

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?).

Allan Elder
  • 4,052
  • 17
  • 19
  • 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!! – Danilo Bambi Nov 11 '14 at 21:18
  • 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. – Allan Elder Nov 11 '14 at 21:20
  • 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!! – Danilo Bambi Nov 11 '14 at 21:39