'ExecuteNonQuery 需要一个开放且可用的连接。连接的当前状态是关闭的。 - C#

'ExecuteNonQuery requires an open and available Connection. The connection's current state is closed.' - C#

代码:

        private void btnSave_Click(object sender, EventArgs e)
        {
            
            using (con = new SqlConnection(connectionString))
            {
                SqlCommand cmd;
                switch (action)
                {
                    case 'a':
                        cmd = new SqlCommand("INSERT INTO tbl_User (userName, userPass) Values (@username, @userpass)", con);
                        cmd.CommandType = CommandType.Text;
                        cmd.Parameters.AddWithValue("@username", txtUN.Text.Trim());
                        cmd.Parameters.AddWithValue("@userpass", txtPW.Text.Trim());
                        cmd.ExecuteNonQuery();
                        cmd.Connection.Close();

                        MessageBox.Show("Added new User Successfully!", "User Maintenance", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        break;
                    case 'u':
                        break;
                    case 'd':
                        break;
                }
            }
            LoadData();
        }

单击保存按钮时出现此错误:

System.InvalidOperationException: 'ExecuteNonQuery requires an open and available Connection. The connection's current state is closed.'

我正在使用 using 关键字,如果我是正确的,using 不会自动打开和关闭 sqlConnection 吗?如果是这样,为什么 returns 出现错误,我需要为 ExecuteNonQuery() 建立一个开放且可用的连接?我怎样才能解决这个问题?我应该只是简单地添加 Open 和 Close 语法吗?或者有更好的方法吗

LoadData() 方法:

public void LoadData()
        {
            //keyword using automatically closes the connection to the sql
            using (con = new SqlConnection(connectionString))
            {
                SqlDataAdapter sda = new SqlDataAdapter("Select * from tbl_User", con);
                DataTable dt = new DataTable();
                sda.Fill(dt);

                DGUserData.DataSource = dt;
            }
        }

您可以简单地使用 con.Open() 这样连接将在关闭状态的情况下建立,或者您可以在打开连接之前添加检查(下面的片段) .

public void LoadData()
        {
            //keyword using automatically closes the connection to the sql
            using (con = new SqlConnection(connectionString))
            {
                  if (con.State == ConnectionState.Closed)
                  con.Open();

                SqlDataAdapter sda = new SqlDataAdapter("Select * from tbl_User", con);
                DataTable dt = new DataTable();
                sda.Fill(dt);
                DGUserData.DataSource = dt;
            }
        }