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
"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 yourcn
has a value which doesn't exist inDataGridView1.Columns
. For example, if you have 2 columns, your indexes are0
and1
. If you try to ask forDataGridView1.Columns(2)
- you will get this exception. So, as mentioned above in comments, when dealing with collections you either useFor Each
loop or you useFor... count -1
loopThis is correct code:
Example of
For Each