在vb中删除SQL数据库行

时间:2015-04-20 15:17:09

标签: sql-server vb.net visual-studio-2010 visual-studio-2012 vbscript

我在删除SQL数据库行以进行下一次删除时遇到问题。 第一次,它正常工作,但第二次,我得到错误消息(命令参数[1]无效)。

我使用datagridview来选择要删除的行(单个/多个)。 这是我的代码:

    Dim response As MsgBoxResult
    Dim i As Integer
    i = DataGridView1.CurrentRow.Index

    If Not Trim(DataGridView1.Item("Group", i).Value.ToString) = "Admin" Then
        response = MsgBox("Do you want remove this account ?" & vbNewLine & "Account : " & Trim(DataGridView1.Item("Name", i).Value.ToString), _
                          MsgBoxStyle.Question + MsgBoxStyle.YesNo, "Delete Data")
        If response = MsgBoxResult.Yes Then
            If Not MyConnection.State = ConnectionState.Open Then
                MyConnection.Open()
            End If
            cmd.Connection = MyConnection
            cmd.CommandText = "DELETE FROM t_User WHERE ID =?"
            cmd.Parameters.AddWithValue("@row", 0)
           For Each UserRow As DataGridViewRow In DataGridView1.SelectedRows
            If Not MyConnection.State = ConnectionState.Open Then
                    MyConnection.Open()
            End If
                cmd.Connection = MyConnection
                cmd.Parameters("@row").Value = UserRow.Cells("ID").Value
                DataGridView1.Rows.Remove(UserRow)
                cmd.ExecuteNonQuery()
                DeleteColumns()
                CreateColumns()
                MyConnection.Close()
           Next UserRow
            Me.BackgroundWorker1.RunWorkerAsync()
        End If
    End If

请帮助我,非常感谢您的帮助

1 个答案:

答案 0 :(得分:0)

不要在for循环中关闭连接。移动这一行:

 MyConnection.Close()

在Next UserRow行之后。

或者,如果您确实需要在每一行之后重新打开连接[这种情况并不常见],那么您需要重做完整的cmd,如

            cmd.Connection = MyConnection
            cmd.CommandText = "DELETE FROM t_User WHERE ID =?"
            cmd.Parameters.AddWithValue("@row", 0)