“连接未关闭,连接的当前状态是打开的”

时间:2014-12-06 21:35:30

标签: vb.net datagridview connection

我有一个从Access数据库填充的datagridview(未绑定)。我有复选框,可以勾选,然后删除记录。我添加了一个名为Update()的子程序,它根据从datagridview中删除的ID更新成员的可用性。当我注释掉Update()时删除工作正常,所以我发现了错误

  

连接未关闭,连接的当前状态已打开

来自这个:

    Public Sub Update()

    For Each row As DataGridViewRow In dgvMember.Rows
        con.Open()
        If row.Cells(3).FormattedValue Then
            Using cmd As New OleDbCommand("UPDATE Members SET Available = 1 WHERE ID = " & (row.Cells(3).FormattedValue) & "", con)
                cmd.CommandType = CommandType.Text
                result = cmd.ExecuteNonQuery
            End Using
        End If
    Next
    con.Close()
End Sub

我几乎尝试过所有事情。 即 If con.State = ConnectionState.Open Then con.Close()

前一天它工作正常并更新了我的数据库中的可用字段,现在它不断出现该错误而不是删除所有记录。我错过了什么吗?为什么要这样做?

2 个答案:

答案 0 :(得分:3)

我建议在连接块中包装连接:

using (SqlConnection connection = new SqlConnection(connectionString))
{
     //etc...
}

或者,在try-finally中添加一个catch块:

conn.Open();

try
{

}
catch
{

}
finally
{
    conn.Close();
}

答案 1 :(得分:0)

问题#1 - 你在循环中调用conn.open。

问题#2 - 没有错误检测/错误处理

建议的替代方案:

Public Sub Update()

try   
  con.Open()
  For Each row As DataGridViewRow In dgvMember.Rows
    If row.Cells(3).FormattedValue Then
        Using cmd As New OleDbCommand("UPDATE Members SET Available = 1 WHERE ID = " & (row.Cells(3).FormattedValue) & "", con)
            cmd.CommandType = CommandType.Text
            result = cmd.ExecuteNonQuery
        End Using
    End If
  Next
Catch ex as Exception
  MsgBox("Can't load Web page" & vbCrLf & ex.Message)
Finally
  if (con.State = ConnectionState.Open) then conn.Close
End Sub

其他建议:检查MSVS IDE中的DataGrid属性,并确保您也没有在那里打开连接。

相关问题