spkelly86
spkelly86

Reputation: 97

Error when creating dynamic two dimensional array in vb.net

I am trying to increase the x value of the 2 dimensional array but I keep receiving this error.

'ReDim' can only change the rightmost dimension

I need to do this while maintaining the data of the array. Here is my code.

            Dim x As Integer = 0
            Dim y As Integer = 0
            While reader.Read()
                ReDim Preserve catagoryInfo(x, 2)
                catagoryInfo(x, y) = reader.GetString(0)
                y += 1
                catagoryInfo(x, y) = reader.GetString(1)
                x += 1
                y = 0
            End While

Upvotes: 1

Views: 3160

Answers (1)

Steve
Steve

Reputation: 216293

In a multidimensional array, you can change only the last dimension when you use Preserve. If you attempt to change any of the other dimensions, a run-time error occurs. A part from this your code is really suboptimal because you are planning to Redim you array at every loop. Redimming with preserve is worse because not only the runtime allocates a new array but it should also copy from the old array to the new array.

In your case is better to declare a simple class like this

Public Class CategoryInfo
    Public info1 As String
    Public info2 As String
End Class

then use a List(Of CategoryInfo)

Dim infos as List(Of CategoryInfo) = new List(Of CategoryInfo)()
While reader.Read()
    Dim nf As CategoryInfo = new CategoryInfo() 
    nf.info1 = reader.GetString(0)
    nf.info2 = reader.GetString(1)
    infos.Add(nf)
    ' if you like the all-in-one-line coding style you could also write the above in this way
    ' infos.Add(New CategoryInfo With {.info1=reader.GetString(0), .info2=reader.GetString(1)} )
End While

Now, if you really need to have your data inside a string array you could write

Dim categoryInfo(infos.Count, 2) as String
for x = 0 to infos.Count -1
    categoryInfo(x,0) = infos(x).info1
    categoryInfo(x,1) = infos(x).info2
next

this is still not very optimal because you loop two times on your data but, at least, it will get your data as you want.

Upvotes: 3

Related Questions