Search code examples
arraysvb.netrecord

VB.Net "Index was outside the bounds of the array." when trying to increment Array element


I have an array of records, defined like this:

Structure TNumTemp
        Dim BKA As String
        Dim Num As Integer
        Dim Name As String
    End Structure
 Dim Tarray(LOF(2) / Len(LocationRecord) - 1) As TNumTemp

When I try to increment Tarray(i).Num using Tarray(i).Num = Tarray(i).Num + 1 I get the error mentioned in the title for some reason! Here is relevant code:

For i = 1 To LOF(2) / Len(LocationRecord)
            FileGet(2, LocationRecord, i)

            Tarray(i - 1).Name = Trim(LocationRecord.LocationName)
            Tarray(i - 1).Num = 0
            For j = 1 To LOF(3) / Len(TournamentRecord)
                FileGet(3, TournamentRecord, j)
                If Trim(TournamentRecord.LocationName) = Trim(Tarray(i - 1).Name) Then
                    Tarray(i).Num = Tarray(i).Num + 1
                End If
            Next
        Next

From my understanding, by the array's bounds it means the number of elements in the array? But it is assigning an element of the array, but an element of one of the structures!?


Solution

  • You declared your array to have elements with indexes 0 through (LOF(2) / Len(LocationRecord) - 1). The most common way to loop through all index values would be to code

    For i = 0 To LOF(2) / Len(LocationRecord) - 1
    

    But you coded

    For i = 1 To LOF(2) / Len(LocationRecord)
    

    In most cases, you compensated for that by using (i-1) instead of (i) as the array index inside the loop, but in the statement that is getting the error you did not. The last time round the loop, i will be (LOF(2) / Len(LocationRecord)) which is one more than the last array index. You need to change the problem statement to

    Tarray(i - 1).Num = Tarray(i - 1).Num + 1