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

  • A+
Category:Languages

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.


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

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: