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)