Hello! I have a dataGridView that displays a data table pulled from mySQL.
I am trying to delete a user-selected row when the user hits the DELETE key.
What is happening is, the delete works (both in the DGV and the actual data table), but it deletes TWO rows (selected & the one above) from the dataGridView (but not from the actual table). When I refresh the DGV, the row above the selected row that wasn't supposed to get deleted re-appears. I want JUST the selected row to be deleted from the DGV.
Could someone tell me how I can fix my code? Thank you!
Code:
Private Sub dgv_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles DataGridView1.KeyDown
If e.KeyCode = Keys.Delete Then
setConnection()
deleteData()
End If
End Sub
Private Sub deleteData()
Try
Dim i As Integer
Dim tableName As String = TableList.Text
Dim mResult
mResult = MsgBox("Do you really want to delete the selected records?", vbYesNo + vbQuestion, "Removal confirmation")
If mResult = vbNo Then
Exit Sub
End If
command = New MySqlCommand
command.Connection = conn
If tableName = "persons" Then
For i = DataGridView1.SelectedRows.Count - 1 To 0 Step -1
command.CommandText = "delete from `" & tableName & "` where `Book ID`=" & DataGridView1.SelectedRows(i).Cells("Book ID").Value & ";"
command.ExecuteNonQuery()
DataGridView1.Rows.Remove(DataGridView1.SelectedRows(i))
Next
ElseIf tableName = "randomdata" Then
For i = DataGridView1.SelectedRows.Count - 1 To 0 Step -1
command.CommandText = "delete from `" & tableName & "` where dataid=" & DataGridView1.SelectedRows(i).Cells("dataid").Value & ";"
command.ExecuteNonQuery()
DataGridView1.Rows.Remove(DataGridView1.SelectedRows(i))
Next
End If
fetchData(tableName)
Catch ex As Exception
MsgBox("Could not delete record. " & ex.Message)
Finally
conn.Close()
End Try
End Sub