Home > Software engineering >  Error when deleting a Row in a DataGridView
Error when deleting a Row in a DataGridView

Time:02-19

I am attempting to delete a row in my DataTable or DataViewGrid and it works, however if I select anywhere on the row other than the entire row itself it throws an error and the code stops. Is there a way to make it so when I select a part of the row and hit delete that the whole row gets deleted or at the very least a If Else statement to make it so the code does not crash if the entire row is not selected?

Here is my code deleting the row on button click.

Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click

    Dim i As Integer = DataGridView1.SelectedRows(0).Index
    DataGridView1.Rows.RemoveAt(i)

End Sub

CodePudding user response:

You can use the following code to delete a Row in a DataGridView.

Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
    If DataGridView1.Rows.Count > DataGridView1.CurrentCell.RowIndex   1 Then
        DataGridView1.Rows.RemoveAt(DataGridView1.CurrentCell.RowIndex)
    End If
End Sub

Or if you want to press 'Delete' key to delete the row:

Private Sub DataGridView1_KeyDown(sender As Object, e As KeyEventArgs) Handles DataGridView1.KeyDown
    If e.KeyCode = Keys.Delete Then
        If DataGridView1.Rows.Count > DataGridView1.CurrentCell.RowIndex   1 Then
            DataGridView1.Rows.RemoveAt(DataGridView1.CurrentCell.RowIndex)
        End If
    End If
End Sub
  • Related