I am trying to fill an array with all the Button
s 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.
If all the Button
s 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
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;
}
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();
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);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With