Index Out Of Range (Range Is Variable)

56 views Asked by At

So I'm trying to return all the column names in my datagridview. The code below returns the column names except at the end, I a message stating Index was out of range I assume this is because I have less than 500 columns in my datagridview.

The 500 could in theory be any amount, some might only have 20 columns, others might have 300 columns.

How would I go about clearing up this error?

Dim c As Integer
    For cn = 0 To 500

        c = c + cn
        'Debug.Print(cn)
        Debug.Print(DataGridView1.Columns(cn).Name)

Next cn
1

There are 1 answers

0
T.S. On BEST ANSWER

"Index out of range" exception can happen when you are trying to access a member of collection under index that doesn't exist

Lets take your example - you getting error here DataGridView1.Columns(cn) because your cn has a value which doesn't exist in DataGridView1.Columns. For example, if you have 2 columns, your indexes are 0 and 1. If you try to ask for DataGridView1.Columns(2) - you will get this exception. So, as mentioned above in comments, when dealing with collections you either use For Each loop or you use For... count -1 loop

This is correct code:

For i as Integer = 0 To DataGridView1.Columns.Count - 1
    Debug.WriteLine(DataGridView1.Columns(i).Name)
Next

Example of For Each

For Each s as String In myStrings  ' myStrings can be List(Of String)
    Debug.WriteLine(s)
Next