• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 1301
  • Last Modified:

VB.NET Datagridview - Index out of range error

I have a datagridview that is working fine.  However, I set a CellDoubleClick to do an event and everytime I accidently click on the header of a column, I get "Index was out of range.  Must be non-negative and less than the size of the collection.  Parameter name:  index".

I would I set it so that it would either exit the event or not give me an unhandled error?  Below is my attempt to exit sub if they click on header, but that's where it error out with the index out of range.
If dgViewDetail.Rows(e.RowIndex).Cells("ID").Value = 0 Then
  Exit Sub
End If

Open in new window

1 Solution
Place this check
If e.RowIndex >= 0 then
   'remain code here
End if

Headers are at index -1.
holemaniaAuthor Commented:
Awesome.  Thank you!!
Fernando SotoRetiredCommented:
Try it like this.
    Private Sub dgViewDetail_CellDoubleClick(ByVal sender As Object, _
        ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles dgViewDetail.CellDoubleClick
        If e.RowIndex < 0 Then Return
        If dgViewDetail.Rows(e.RowIndex).Cells("ID").Value = 0 Then
            Exit Sub
        End If
    End Sub

Open in new window

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Get expert help—faster!

Need expert help—fast? Use the Help Bell for personalized assistance getting answers to your important questions.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now