Hi, I need to loop through a bunch of picture boxes that I have, all with names such as:

PictureBox00, PictureBox01, PictureBox02 etc.

I need to loop through these and adjust their values by what the current value in the loop is, I basically want to do this to it:

for (int i = 0; i < 3; i++)
PictureBox(i).enabled = false;

I need to access them like an array, I will not know what picturebox I would be dealing with at that time, only way I can see to do this is by using the loop, cheers.

EDIT: I think this was pretty easy to do in VB.NET via DirectCast, not sure if that would be used here(the similar version).

Edited by Bountyhuntr: n/a

7 Years
Discussion Span
Last Post by ddanbe

Hi, Bountyhuntr, welcome at daniweb :)
Perhaps this C# snippet can solve your problem.

I don't think that will help me as I need to access the correct picturebox which matches the current counter in the loop, i.e on the 3rd loop it needs to be the 3rd textbox which is why I chose the names for the textbox, hoping I could access the textbox number which corrisponds to the counter.


You can get a list of the PictureBoxes in the Controls collection using the linq extension method OfType.
Then sort the list to get them in name order.

var myPics = this.Controls.OfType<PictureBox>().ToList();
myPics.Sort((a, b) => { return a.Name.CompareTo(b.Name); });

You should only need to do this once, in the form constructor after the Initialize method.

Votes + Comments
He! Thanks for the tip! :)

@nick.crane: great code , my snippet dates from the time before I knew of the existance of LINQ.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.