DataGridview和MySQL使用Checkbox删除行

时间:2013-02-11 23:22:50

标签: mysql vb.net datagridview

我有一个Datagridview,我想在我的MySQL数据库中删除一行。

我有一些代码,但是我收到错误,它说ID为null。我的ID是一个字符串,它是检查列的ID的值。我的第一列“第0列”是一个复选框列

以下是代码:

如果您不明白我的要求,请随意提出具体问题。

Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)        Handles Button2.Click
Dim RowsToDelete As New List(Of DataGridViewRow)




Try
For Each row As DataGridViewRow In DataGridView1.Rows

If row.Cells(0).Value = True Then

DeleteRow(row.Cells(1).Value)
RowsToDelete.Add(row)
End If
Next
Catch ex As Exception
MessageBox.Show(ex.ToString)
End Try


For Each rowtodelete In RowsToDelete
DataGridView1.Rows.Remove(rowtodelete)

next       


End Sub

Private Sub DeleteRow(ByVal ID As Integer)
Dim MySQLCon As New MySqlConnection
Dim ConnectionString As String = "server=localhost;user id=root;password=;database=business elements"

MySQLCon.ConnectionString = ConnectionString
Dim CMD As MySqlCommand
MySQLCon.Open()
Try
CMD.Connection = MySQLCon
CMD.CommandText = "DELETE FROM `users` WHERE `ID` = " & ID

Catch ex As Exception

End Try

MySQLCon.Close()
MySQLCon.Dispose()
End Sub

2 个答案:

答案 0 :(得分:0)

如果没有看到所有代码,那么这样的代码应该可行:

Dim sql as String

sql = "DELETE FROM `users` WHERE `ID` IN ("

For Each row As DataGridViewRow In DataGridView1.Rows
    If row.Cells(0).Value = True Then
        ID = row.Cells(1).Value
        DeleteRow(row.Cells(1).Value) 
        RowsToDelete.Add(row)
        sql += ID + ","
    End If
Next

If sql.Left(sql.Length-1) = "," Then
   CMD.CommandText = sql.Left(sql.Length-1) + ")"
   CMD.Connection = MySQLCon
   CMD.ExecuteNonQuery()
End If
祝你好运。

答案 1 :(得分:0)

终于找到了代码:

Private Sub Button2_Click(ByVal sender As System.Object,ByVal e As System.EventArgs)处理Button2.Click         Dim RowsToDelete作为新列表(DataGridViewRow)

    Try
        For Each row As DataGridViewRow In DataGridView1.Rows

            If row.Cells(0).Value = True Then

                DeleteRow(row.Cells(1).Value)
                RowsToDelete.Add(row)
            End If
        Next
    Catch ex As Exception
        MessageBox.Show(ex.ToString)
    End Try


    For Each rowtodelete In RowsToDelete
        DataGridView1.Rows.Remove(rowtodelete)

    Next



End Sub

Private Sub DeleteRow(ByVal ID As Integer)
    Dim MySQLCon As New MySqlConnection
    Dim ConnectionString As String = "server=localhost;user id=root;password=;database=business elements"
    MySQLCon.ConnectionString = ConnectionString
    Dim CMD As New MySqlCommand
    CMD.CommandText = "DELETE FROM `users` WHERE `ID` = " & ID
    MySQLCon.Open()
    Try
        CMD.Connection = MySQLCon

        CMD.ExecuteNonQuery()

    Catch ex As Exception

    End Try







    MySQLCon.Close()
    MySQLCon.Dispose()
End Sub