Home > Mobile >  How to create a List of Existing Buttons?
How to create a List of Existing Buttons?

Time:01-27

I have created a 100 buttons on Windows Forms using Toolbox and I have given them a specific name for each row and column for example the first row is called A and first column is called 1 , the last row ends with the letter J and the last column ends with the number 10 . So it appears as a 10x10 array. What I am trying to do is add those buttons into a list either with a loop . On properties under design I have given them their equivalent name to make it easier. What would be the best way to add them into a list ?

CodePudding user response:

They're already in a "list" in that to appear on the Form they must be a member of some existing Control's .Controls collection, and you can query it. Suppose they're just straight on the Form, not in a Panel etc:

this.Controls.OfType<Button>()

If you truly want a List<Button>, add .ToList() onto the end

--

If you have other buttons on the Form that you don't want being returned, then pick on something common about those buttons you do want, like "they all have a two-character name":

this.Controls.OfType<Button>().Where(b => b.Name.Length == 2)

Of course, if you've also stuck a Button called OK, then this is defeated - but the "something common about them that no other button has" is something you can influence - rename your OK button if it's being picked up accidentally


If they're in their own Panel, it could be a good way of segregating them from other Buttons:

thePanelName.Controls.OfType<Button>()
  •  Tags:  
  • Related