0

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

我有一些代码,但我收到一个错误,它说 ID 为空。我的 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

4

2 回答 2

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

祝你好运。

于 2013-02-11T23:43:31.880 回答
0

终于找到了代码:

Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) 处理 Button2.Click Dim RowsToDelete 作为新列表(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 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
于 2013-02-12T00:13:18.187 回答