Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Fill an array with all the buttons being used in Windows form

Tags:

c#

winforms

I am trying to fill an array with all the Buttons being used in Form1.

Button[] ButtonArray = new Button[5];

ButtonArray[0] = button1;   
ButtonArray[1] = button2;   
ButtonArray[2] = button3;   
ButtonArray[3] = button4;   
ButtonArray[4] = button5;

This code works fine. But if I have for example 100 buttons it is a long procedure.

like image 832
Clayton Avatar asked May 17 '18 12:05

Clayton


4 Answers

If all the Buttons are on the form you can try using Linq:

using System.Linq;

...

Button[] ButtonArray = Controls
  .OfType<Button>()
  .ToArray();

Edit: in case you have some buttons within groupboxes, panels (i.e. not directly on the form, but on some kind of container), you have to elaborate the code into something like this

private static IEnumerable<Button> GetAllButtons(Control control) {
  IEnumerable<Control> controls = control.Controls.OfType<Control>();

  return controls
    .OfType<Button>()
    .Concat<Button>(controls
       .SelectMany(ctrl => GetAllButtons(ctrl)));
}

...

Button[] ButtonArray = GetAllButtons(this).ToArray();

See How to get ALL child controls of a Windows Forms form of a specific type (Button/Textbox)? for details

like image 141
Dmitry Bychenko Avatar answered Oct 16 '22 07:10

Dmitry Bychenko


you can try this one:

ButtonArray[] buttonArray = new ButtonArray[this.Controls.OfType<Button>().Count()]
int i =0; //index for button array
foreach(var button in this.Controls.OfType<Button>()) //Iterate through each button control
{
    buttonArray [i++] = button;
}
like image 39
Prasad Telkikar Avatar answered Oct 16 '22 08:10

Prasad Telkikar


Enumerable.OfType doesn't search controls down the control-hierarchy. So if you want to find controls recursively you could use this extension method:

public static IEnumerable<T> RecursiveControlsOfType<T>(this Control rootControl) where T : Control
{
    foreach (Control child in rootControl.Controls)
    {
        if (child is T targetControl)
            yield return targetControl;
        foreach (T targetControlChild in child.RecursiveControlsOfType<T>())
            yield return targetControlChild;
    }
}

Usage:

Button[] nonRecursiveButtons = this.Controls.OfType<Button>().ToArray();
Button[] recursiveButtons = this.RecursiveControlsOfType<Button>().ToArray();
like image 41
Tim Schmelter Avatar answered Oct 16 '22 07:10

Tim Schmelter


List<Button> Buttons = new List<Button>();
foreach (var item in this.Controls) // Looping through all controls in the form
{
    if (item is Button) // if the current is a button we add it
    {
        Buttons.Add(item as Button);
    }
}
like image 28
Nothing Mattress Avatar answered Oct 16 '22 07:10

Nothing Mattress