0

The code below opens a detailed view of a leader when a specific cell is clicked. I am trying to make it so when a cell is clicked it adds the row position of any event that has the LeaderID of the selected cell to the array "le". I know there is other ways of doing certain things but I have already done this way and it worked until I edited it and used the if statement shown below.

However this line of code

If dgdEvents.Rows(n).Cells("LeaderID").Value = .Rows(i).Cells("LeaderID").Value Then

Is causing the following error

An unhandled exception of type 'System.ArgumentOutOfRangeException' occurred in mscorlib.dll

Additional information: Index was out of range. Must be non-negative and less than the size of the collection.

Code:

Public Sub dgdLeaders_CellClick(sender As Object, e As DataGridViewCellEventArgs) Handles dgdLeaders.CellClick
    dbv.EditLeader()
    Dim i As Integer
    Dim n As Integer
    Dim c As Integer = 0
    With dgdLeaders
        If e.RowIndex >= 0 Then
            i = .CurrentRow.Index
            While n <> dgdEvents.Rows.Count + 1
                If dgdEvents.Rows(n).Cells("LeaderID").Value = .Rows(i).Cells("LeaderID").Value Then
                    le(c) = n
                    c = c + 1
                End If
                n = n + 1
            End While
            tbid.Text = .Rows(i).Cells("LeaderID").Value.ToString
            tbfn.Text = .Rows(i).Cells("Forename").Value.ToString
            tbsn.Text = .Rows(i).Cells("Surname").Value.ToString
            dtpdob.Value = .Rows(i).Cells("DOB").Value
            tbsr.Text = .Rows(i).Cells("Role").Value.ToString
            tbpc.Text = .Rows(i).Cells("Postcode").Value.ToString
            tbht.Text = .Rows(i).Cells("HomeTel").Value.ToString
            tbmt.Text = .Rows(i).Cells("MobileTel").Value.ToString
            tbal1.Text = .Rows(i).Cells("AddressLine1").Value.ToString
            tbal2.Text = .Rows(i).Cells("AddressLine2").Value.ToString
            tbc.Text = .Rows(i).Cells("City").Value.ToString
            tbea.Text = .Rows(i).Cells("EmailAddress").Value.ToString
            l = i
            n = 0
        End If
    End With
End Sub
Community
  • 1
  • 1
  • Probably because your also trying to access the last row which is an editable row in a DGV try adding: `dgdEvents.AllowUserToAddRows = False` then use a for to go through the row is much easier than increment – Mederic Apr 24 '17 at 11:47
  • 3
    You will need to debug this. I'm not sure what `While n <> dgdEvents.Rows.Count + 1` is doing but the norm is `dgdEvents.Rows.Count - 1`. Probably better to use `For n = 0 To dgdEvents.Rows.Count - 1`. – Bugs Apr 24 '17 at 11:49

0 Answers0