1.11M Members

How to loop through controls(different).

 
0
 

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

 
0
 

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

 
0
 

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.

 
0
 

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

 
1
 

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.

 
0
 

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

You
This article has been dead for over six months: Start a new discussion instead
Post:
Start New Discussion
View similar articles that have also been tagged: