1,105,363 Community Members

How to loop through controls(different).

Member Avatar
Bountyhuntr
Newbie Poster
2 posts since Aug 2011
Reputation Points: 0 [?]
Q&As Helped to Solve: 0 [?]
Skill Endorsements: 0 [?]
 
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).

Member Avatar
ddanbe
Posting Expert
5,355 posts since Oct 2008
Reputation Points: 2,066 [?]
Q&As Helped to Solve: 908 [?]
Skill Endorsements: 46 [?]
Featured
 
0
 

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

Member Avatar
Bountyhuntr
Newbie Poster
2 posts since Aug 2011
Reputation Points: 0 [?]
Q&As Helped to Solve: 0 [?]
Skill Endorsements: 0 [?]
 
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.

Member Avatar
ddanbe
Posting Expert
5,355 posts since Oct 2008
Reputation Points: 2,066 [?]
Q&As Helped to Solve: 908 [?]
Skill Endorsements: 46 [?]
Featured
 
0
 

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

Member Avatar
nick.crane
Veteran Poster
1,195 posts since Feb 2010
Reputation Points: 342 [?]
Q&As Helped to Solve: 190 [?]
Skill Endorsements: 5 [?]
 
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.

Member Avatar
ddanbe
Posting Expert
5,355 posts since Oct 2008
Reputation Points: 2,066 [?]
Q&As Helped to Solve: 908 [?]
Skill Endorsements: 46 [?]
Featured
 
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 three months: Start a new discussion instead
Post:
Start New Discussion
View similar articles that have also been tagged: