Reputation: 93
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)
Upvotes: 0
Views: 413
Reputation: 4094
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?).
Upvotes: 2