Computer User
Computer User

Reputation: 2869

iterate control names using a counter

I have over 100 buttons in a windows form an I want to access their name for command Button.PerformClick() based on the counter in a for loop. For example: Button + Convert.Tostring(Counter).PerformClick() How do I do this?

Upvotes: 0

Views: 288

Answers (1)

Selman Genç
Selman Genç

Reputation: 101681

You can use OfType extension method to loop through all of your buttons:

foreach(var button in this.Controls.OfType<Button>())
{
    // do something with button
    button.PerformClick();
}

For loop version:

for(int i=0; i<counter; i++)
{
   string name = "Button" + i;
   if(this.Controls.ContainsKey(name))
   {
      var currentButton = this.Controls[name] as Button;
   }
}

Note: This answer assumes that your buttons are direct child elements of your Form.If Buttons inside of a Panel then you should access ControlCollection of your panel with panelName.Controls instead of this.Controls.

Upvotes: 6

Related Questions