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).

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

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.

Is it not possible to extract the number out of the PictureBox Name with the substring method?

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.

commented: He! Thanks for the tip! :) +14

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

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.