I am using Visual Studio 2013 and SQL Server 2012. I want to save my data in the database but it gives:

An unhandled exception of type 'System.InvalidOperationException' occurred in System.Data.dll

My code:

private void button1_Click(object sender, EventArgs e)
    {
        string connString = ConfigurationManager.ConnectionStrings["dbx"].ConnectionString;
        using (SqlConnection conn = new SqlConnection(connString))
        {
            using (SqlCommand cmd = new SqlCommand("ups_StudentInsertDetails"))
            {
                cmd.Parameters.AddWithValue("Name", textBox1.Text);
                cmd.Parameters.AddWithValue("Email", textBox2.Text);
                //then open connection
                conn.Open();
                //Execute Reader(select ststement)
                //Execute Scalar(select ststement)
                //Executenonquery (Insert , update or delete)
                cmd.ExecuteNonQuery();
                MessageBox.Show("Data saved successfully!");

            }
        }

    }
}

Error: error

2

There are 2 best solutions below

0
On

Open your sqlconnection like this and associate it with the sqlcommand. See the code changes below highlighted in comments.

Private void button1_Click(object sender, EventArgs e)
{
    string connString = ConfigurationManager.ConnectionStrings["dbx"].ConnectionString;
    using (SqlConnection conn = new SqlConnection(connString))
    {
    conn.open();  //Open Connection
        using (SqlCommand cmd = new SqlCommand("ups_StudentInsertDetails",conn)) //Pass connection to thesqlcommand
        {
            cmd.Parameters.AddWithValue("Name", textBox1.Text);
            cmd.Parameters.AddWithValue("Email", textBox2.Text);
            cmd.ExecuteNonQuery();
            MessageBox.Show("Data saved successfully!");
        }
    }

}

}

0
On

SqlCommand does not contain the SqlConnection you are opening. in the first place. You can make the code easier to drop the second using and open the connection at the command before executing it:

 private void button1_Click(object sender, EventArgs e)
 {
     string connString = ConfigurationManager.ConnectionStrings["dbx"].ConnectionString;
     using (SqlConnection conn = new SqlConnection(connString))
     {
         SqlCommand cmd = new SqlCommand("ups_StudentInsertDetails", conn);
         cmd.Parameters.AddWithValue("Name", textBox1.Text);
         cmd.Parameters.AddWithValue("Email", textBox2.Text);

         //then open connection
         cmd.Connection.Open();

         cmd.ExecuteNonQuery();
         MessageBox.Show("Data saved successfully!");
    } 
 }

More info on the MSDN website with example at the bottom