Home > Enterprise >  the codes shows a notif 'Index was out of range. Must be non-negative and less than the size of
the codes shows a notif 'Index was out of range. Must be non-negative and less than the size of

Time:12-07

Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
        Cursor = Cursors.AppStarting
        Dim id As Integer
        Dim fx As frmItemEntry
        id = DataGridView1.SelectedRows(0).Cells("id").Value
        fx = New frmItemEntry(id)
        Button4.PerformClick()
        fx.ShowDialog()
        Cursor = Cursors.Default
    End Sub

try this code from a blog but, am don't know where is wrong

CodePudding user response:

Obviously no rows are selected. Therefore you cannot access row 0. The best way to deal with this situation is to disable the button when no row is selected.

To do this you must handle the SelectionChanged event

Private Sub DataGridView1_SelectionChanged(ByVal sender As Object, ByVal e As EventArgs) _
   Handles DataGridView1.SelectionChanged

   Button2.Enabled = DataGridView1.SelectedRows.Count > 0
End Sub

Also, disable the button by default in the Form designer. This code will enable it whenever a selection is made.


Another possibility is to do something like this:

Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
    Dim id As Integer
    Dim fx As frmItemEntry

    If DataGridView1.SelectedRows.Count > 0 Then
        Cursor = Cursors.AppStarting
        id = DataGridView1.SelectedRows(0).Cells("id").Value
        fx = New frmItemEntry(id)
        Button4.PerformClick()
        fx.ShowDialog()
        Cursor = Cursors.Default
    Else
        MessageBox.Show("Please select a row")
    End If
End Sub
  • Related