ExecuteNonQuery not working in C#

Ivan Fernandez picture Ivan Fernandez · Jun 3, 2013 · Viewed 11.5k times · Source

I am building a database using Visual Studio 2008 c# and when I'm a trying to insert a new record into my database it appears that ExecuteNonQuery has not initialized. I copy my code, hope anyone can help me in this because I am new.

 private void button1_Click(object sender, EventArgs e)
 {
     SqlConnection cn = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Users\Usuario\Documents\Visual Studio 2010\Projects\Nova\Nova\Database1.mdf;Integrated Security=True;User Instance=True");
     SqlCommand cmd = new SqlCommand();
     cn.Open();
     cmd.CommandText = "insert into Database1.mdf(Codigo,Nombre,Cantidad,Tipo) values('"+comboBox1.Text+"','"+textBox3.Text+"','"+textBox1.Text+"','"+comboBox2.Text+"')";
     cmd.ExecuteNonQuery();
     cmd.Clone();
     cn.Close();
     MessageBox.Show("Acabas de agregar un producto");
 }

Answer

Fabian Bigler picture Fabian Bigler · Jun 3, 2013

You haven't set the connection to your command:

cmd.Connection = cn;