Can an empty array be iteratively extended?

D

Dean Slindee

I want to build an array on the fly in code with a parameter passed for the
number of elements in the array. I am trying to do this by looping, but
get an array with just one element in the end.
Can this be done my way or some other way?

Dim idx As Integer

Dim cnt As Integer = 5 'parm for # of elements

Dim picArray As PictureBox()

For idx = 0 To cnt - 1

picArray = New PictureBox() {New PictureBox} 'one element

picArray(idx) = New PictureBox() {New PictureBox} 'bad syntax

Next

idx = picArray.GetUpperBound(0)

'when above works, then do this:

For idx = 0 To cnt - 1

picArray(idx).BorderStyle = BorderStyle.FixedSingle

picArray(idx).BackColor = SystemColors.Control

picArray(idx).Height = size

picArray(idx).Width = size

Next



Thanks,

Dean Slindee
 
H

Herfried K. Wagner [MVP]

* "Dean Slindee said:
I want to build an array on the fly in code with a parameter passed for the
number of elements in the array. I am trying to do this by looping, but
get an array with just one element in the end.
Can this be done my way or some other way?

Instead of using an array (can be changed in size without loosing its
elements with 'ReDim Preserve'), use an 'ArrayList'. You can add
elements to the arraylist by passing them to the arraylist's 'Add'
method.
 
J

Jay B. Harlow [MVP - Outlook]

Dean,
I want to build an array on the fly in code with a parameter passed for the
number of elements in the array.
Is the number of elements fixed based on a parameter? If so, then you can
use something like the following, however if the number of elements are
unknown and you want an "array" that can change size I would do as Herfried
suggests & use Redim Preserve or an ArrayList (I favor an ArrayList over
Redim Preserve as its easier).

Have you tried something like:

Public Sub MakeArray(ByVal cnt As Integer)
Dim picArray(cnt - 1) As PictureBox
Dim idx As Integer

For idx = 0 To cnt - 1
picArray(idx) = New PictureBox()

picArray(idx).BorderStyle = BorderStyle.FixedSingle
picArray(idx).BackColor = SystemColors.Control
picArray(idx).Height = size
picArray(idx).Width = size
Next

End Sub

Note that arrays in VB.NET are "off by one", you give the high bound on the
Dim, not the number of elements, hence the "cnt - 1" on the Dim picArray.

Hope this helps
Jay
 
D

Dean Slindee

Jay,
Yes, that does the trick! I had (erroneously) boxed myself in with the
notion that the picArray()had to be Dim'd (scoped) at the form-level in
order to be able show the picArray in a panel on the form. Ah, scope freedom
is a wonderful thing.
Thanks,
Dean
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top