Joe Moore
Joe Moore

Reputation: 2023

How do you load every PictureBox on a form into an array?

I'm currently trying to find a way to change every PictureBox on my form to have the same image. I have achieved this, but its messy, and I was wondering if there is a 'cleaner' way to do this (As I will need to dynamically fill the PictureBox array later on in my project).

Dim pbxCollection() As PictureBox = {PictureBox1, PictureBox2, PictureBox3, PictureBox4, PictureBox5, PictureBox6, PictureBox7, PictureBox8, PictureBox9} 'collection of all pictureboxes

For Each pbx In pbxCollection 'iterates through the PictureBox array and changes each value
   pbx.Image = My.Resources.<image file name here>
Next

The above code does what I want, but as you can see, I have 9 PictureBoxes. In future I will need to have any number of PictureBoxes up to 50, so this solution will no longer work then.

If there is a way to fill an array with every PictureBox on a form, I will be extremely grateful.

Thanks.

Upvotes: 0

Views: 60

Answers (1)

Joel Coehoorn
Joel Coehoorn

Reputation: 416121

Don't use an array, use an IEnumerable:

Dim pbxCollection = MyForm.Controls.OfType(Of PictureBox)()

Of course this is not recursive, so if there's a panel or group box you want to account for use that instead of MyForm. Also, make sure you run it after the InitializeComponent() method.


From the comments:

I'm using a tableLayoutPanel

So assuming a name of tableLayoutPanel1, it might look something like this:

Dim pbxCollection = tableLayoutPanel1.Controls.OfType(Of PictureBox)()

Upvotes: 2

Related Questions