tags:

views:

1947

answers:

5

on my winform at runtime i will be resizing my array each time i add an element. so first i must resize to the size + 1, and then add a member to this index. how do i do this?

+1  A: 

Use the Redim command to specify the new size.

Redim(MyArray, MyArray.Length + 1)
Dillie-O
this one doesnt work, it gives me Error 1 'ReDim' statements require a parenthesized list of the new bounds of each dimension of the array.
I__
thanks got it to work this way Redim MyArray, (MyArray.Length + 1)
I__
A: 

I would prefer some type of collection class, but if you WANT to use an array do it like this:

dim arr() as integer
dim cnt as integer = 0
dim ix as integer

for ix = 1 to 1000
    cnt = cnt+1
    redim arr(cnt)
    arr(cnt-1) = ix
next
tekBlues
+7  A: 

You could use the ReDim statement, but this really isn't your best option. If your array will be changing sizes often, especially as it sounds like you're just appending, you should probably use a generic List(Of T) or similar collection type.

You can use it just like you use an array, with the addition that adding an item to the end is as easy as MyList.Add(item)

To use a generic list, add Imports System.Collections.Generics to the top of the file. Then, you would declare a new integer list like this:

Dim MyList As New List(Of Integer)()

or a string list like this:

Dim MyList As New List(Of String)()

You should get the idea.

Joel Coehoorn
hi joel! you're right this is the best solution. can you please show me how to declare a list?
I__
Oh yes, definitely +1 for List<T>. I should have asked if you had other object options available first. 8^D
Dillie-O
A: 

As Joel says, use a list.

Dim MyList As New List(Of String)

Don't forget to change Of String to be Of whichever datatype you're using.

dsas
+1  A: 

The suggested ReDim's need the Preserve keyword for this scenario.

ReDim Preserve MyArray(n).

Jules