4

is there a simple way of creating a button collection from the existing buttons on my form? (In c#).

I have a series of buttons already on my form and I want to use an index to access them...e.g.:

myButtonArray[0].ForeColor ...// Do something with it

Can this be done?

Edit: Can I set the array to have a generic OnClick event? And then determine which button in the array was clicked and, say, change its color?

8 Answers 8

6

LINQ to the rescue!!

Button[] buttons = this.Controls.OfType<Button>().ToArray();
Sign up to request clarification or add additional context in comments.

4 Comments

On the other hand, you then have no idea which one is which. It also won't find buttons which are in panels etc.
That is certainly a good point. Luckily for me the requirements don't say there are buttons inside of panels. :)
@Jon: Linq to the rescue again; if you know the button's text or tag, you can use something like buttons.FirstOrDefault(b=>b.Text = "Button Text");
It depends on problem - if you need full control over them better to use predefinde array, but other thing if you need to set same style in the loop for all buttons LINQ is good
3

You can do it the same way as for any other array. For example:

Button[] array = { firstButton, secondButton };

or if you need to declare in one place and assign later:

Button[] array;
...
array = new Button[] { firstButton, secondButton };

In C# 3+ you can use implicit typing for array initializers:

Button[] array;
...
array = new[] { firstButton, secondButton };

You might also want to consider using a List<Button> instead:

List<Button> buttons = new List<Button> { firstButton, secondButton };

Comments

3
var myButtonArray = new [] {this.Button1, this.Button2, ...}

To streamline this process if there are a lot of Buttons, you could try this code at the form level:

this.Controls.OfType<Button>().ToArray();

You could recurse this with any Control in the Controls collection that has a nonempty Controls collection itself.

Comments

1

something like:

var myButtonArray = new[] {btn1, btn2, btn3, btn4};

Comments

1

You have all your controls in the Controls property of your form, so you have to iterate that collection and add it to your array.

List<Button> buttons = new List<Button>();

foreach(Control c in this.Controls)
{
    Button b = c as Button;
    if(b != null)
    {
        buttons.Add(b);
    }
}

Comments

1

In response to your requirements: (Edit: Can I set the array to have a generic OnClick event? And then determine which button in the array was clicked and, say, change its color?)

List<Button> buttons = new List<Button> { firstButton, secondButton };

// Iterate through the collection of Controls, or you can use your List of buttons above.
foreach (Control button in this.Controls)
{
    if (button.GetType() == typeof(Button)) // Check if the control is a Button.
    {
        Button btn = (Button)button; // Cast the control to Button.
        btn.Click += new System.EventHandler(this.button_Click); // Add event to button.
    }
}

// Click event for all Buttons control.
private void button_Click(Button sender, EventArgs e) 
{
    ChangeForeColor(sender); // A method that accepts a Button
    // other methods to do...
    // you can also check here what button is being clicked 
    // and what action to do for that particular button.
    // Ex:
    //
    // switch(sender.Name)
    // {
    //     case "firstButton":
    //         sender.ForeColor = Color.Blue;
    //         break;
    //     case "secondButton ":
    //         sender.Text = "I'm Button 2";
    //         break;
    // }
}

// Changes the ForeColor of the Button being passed.
private void ChangeForeColor(Button btn)
{
    btn.ForeColor = Color.Red;
}

Comments

1

If you are using C# 7.0 or higher you can use the is keyword to check if each control is a button as you loop through them.

List<Button> buttons = new List<Button>();//CREATE LIST FOR BUTTONS

//LOOP THROUGH EACH CONTROL ON FORM
foreach (Control c in Controls)
{
    //IF THE CONTROL IS A BUTTON ADD IT TO THE LIST
    if (c is Button b)
    {
        buttons.Add(b);
    }
}

For older versions of C# please see @Edgar Hernandez's answer

Comments

0

Assuming there is a naming convention...

List<Button> asdf = new List<Button>();
for (int x = 0; x <= 10; x++) {
    asdf.Add(myButton + x);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.