未处理的异常发生在c#中system.data.dll中发生的类型为'system.invalidoperationexception'的未处理异常

时间:2017-10-12 05:00:17

标签: c#

我正在使用Visual Studio 2013和SQL Server 2012.我想将数据保存在数据库中,但它提供了:

  

System.Data.dll中出现未处理的“System.InvalidOperationException”类型异常

我的代码:

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

2 个答案:

答案 0 :(得分:2)

像这样打开你的sqlconnection并将它与sqlcommand相关联。 请参阅以下注释中突出显示的代码更改。

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!");
        }
    }

}

}

答案 1 :(得分:1)

SqlCommand不包含您要开放的SqlConnection。首先。您可以使代码更容易删除,并在执行命令之前打开连接:

 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