using a variable to name a control

  • Thread starter Thread starter AJ
  • Start date Start date
A

AJ

Hi,
I have 20 pictureBoxes named from PictureBox1 to
PictureBox20. I want to fill them up one by one. I'm
keeping a variable firstAvail to keep up with which
pictureBox I should insert the next image into. But how do
I actually access a PictureBox using firstAvail?

I'm thinking I should be able to do something like
PictureBox[firstAvail], but I know that is not the correct
syntax.

Thanks!
 
Why not add the PictureBoxes to a Panel and then you could loop through each
of them without having to know their name up front. You could find out what
the name is as you loop through them.
 
AJ said:
I'm thinking I should be able to do something like
PictureBox[firstAvail], but I know that is not the correct
syntax.

Generally speaking you create either a collection or an array of PictureBox
controls and add a reference for each PictureBox to it. Then you have the
ability to address them like you do any collection (or array.) Think about
if you were creating an array of 20 strings and wanted to print the value of
StringArray[ 2 ] it isn't any different to create an array of 20 picture
boxes and to reference the PictureBox reference through the array index.

Tom
 
AJ said:
Hi,
I have 20 pictureBoxes named from PictureBox1 to
PictureBox20. I want to fill them up one by one. I'm
keeping a variable firstAvail to keep up with which
pictureBox I should insert the next image into. But how do
I actually access a PictureBox using firstAvail?

I'm thinking I should be able to do something like
PictureBox[firstAvail], but I know that is not the correct
syntax.

Create an array of 20 PictureBoxes and loop through it.
 
AJ,
I would consider using a System.Collections.Queue object to maintain the
list of available PictureBoxes. As a Queue works as a FIFO list.

Queue.Enqueue will add items to the end of the list
Queue.Dequeue will remove items from the front of the list.

Before I added any images I would use the Queue.Enqueue method to load each
PictureBox into the Queue

Private m_available As Queue
Public Sub New()
...
InitializeComponent()

' we know there are 30 picture boxes
m_available = New System.Collections.Queue(20)
m_available.Enqueue(PictureBox1)
m_available.Enqueue(PictureBox2)
...
m_available.Enqueue(PictureBox19)
m_available.Enqueue(PictureBox20)

End Sub

Then when I had a picture to load I would Dequeue the next available
PictureBox.

Public Sub NextPicture(image as Image)
Dim pictureBox as PictureBox = DirectCast(m_available.Dequeue(),
PictureBox)
pictureBox.Image = image
End Sub

This also allows adding a PictureBox back into the list of available
PictureBoxes.

Public Sub FreePicture(pictureBox As PictureBox)
pictureBox.Image = Nothing
m_available.Enqueue(pictureBox)
End Sub

Of course this means that if you use 1 to 5, then 1 becomes available, that
6 to 20 will need to be used before 1 is reused.

Hope this helps
Jay
 
Back
Top