-2

I keep having the following error:

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

I am not able to insert into my database as well.

enter image description here

private void btnXoa_Click(object sender, EventArgs e)
{
    SqlConnection conn = new SqlConnection(chuoiKetnoi);
    if (MessageBox.Show("Bạn có chắc chắn muốn xóa ?", "Thông báo", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
    {
        // Thuc hien xoa du lieu
        string delete = "delete from tblKET_QUA where MaSV='" + txtMaSinhVien.Text + "' and MaMH='" + cbbMonHoc.Text + "' ";
        using SqlCommand cmd = new SqlCommand(delete, conn);
        cmd.ExecuteNonQuery();
        MessageBox.Show("Xóa dữ liệu thành công", "Thông báo!");

        // Trả tài nguyên
        cmd.Dispose();
        //Load lai du lieu
        load();
    }
}
Yong Shun
  • 35,286
  • 4
  • 24
  • 46

1 Answers1

5

The error message is clear to mention what you need to do. Your SQL connection is not open. You need to open it before executing the query.

conn.Open();

Reference: SqlConnection.Open


Recommendation(s)

  1. Use Parameterized Query instead of concatenating value into query. This aimed to prevent SQL injection (Example: Bobby-tables) which is highly discussed in the StackOverflow community.
  2. Apply using declaration/block for SqlConnection conn for disposing the connection automatically when it ends.
  3. Remove cmd.Dispose() as you apply using declaration/block for SqlCommand cmd. The disposal will be automatically handled by using.
using SqlConnection conn = new SqlConnection(chuoiKetnoi);
if (MessageBox.Show("Bạn có chắc chắn muốn xóa ?", "Thông báo", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
    conn.Open();

    // Thuc hien xoa du lieu
    string delete = "delete from tblKET_QUA where MaSV = @MaSV and MaMH= @MaMH";
    using SqlCommand cmd = new SqlCommand(delete, conn);
    
    cmd.Parameters.Add("@MaSV", /* SqlDbType */).Value = txtMaSinhVien.Text;
    cmd.Parameters.Add("@MaMH", /* SqlDbType */).Value = cbbMonHoc.Text;
    cmd.ExecuteNonQuery();
    MessageBox.Show("Xóa dữ liệu thành công", "Thông báo!");

    //Load lai du lieu
    load();
}
Yong Shun
  • 35,286
  • 4
  • 24
  • 46