-1

I have wrote code in vb.net to move to the previous row in datagridview when it reaches to first record and when I click again it generates an "index is out of range" error.

Dim i As Integer = DataGridView1.CurrentRow.Index - 1

Me.DataGridView1.CurrentCell = Me.DataGridView1.Rows(i).Cells(0)
Me.DataGridView1.Rows(i).Selected = True 
Robert
  • 7,394
  • 40
  • 45
  • 64
  • Add a line after `Dim i As Integer = DataGridView1.CurrentRow.Index - 1` The line is ` If i < 0 Then i = 0` – Mary Sep 18 '19 at 08:08
  • Still facing the same problem, when i used that instruction that you have given it directly moves the else part which is 'no more rows'. – Tariq Ghafori Sep 19 '19 at 16:19

1 Answers1

0
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Dim i As Integer = DataGridView1.CurrentRow.Index - 1
    If i < 0 Then i = 0
    DataGridView1.CurrentCell = Me.DataGridView1.Rows(i).Cells(0)
    DataGridView1.Rows(i).Selected = True
End Sub

Works for me without error.

Mary
  • 14,926
  • 3
  • 18
  • 27