You can data bind the intended buttons e.g.
using System; using System.Windows.Forms; namespace Demo { public partial class Form1 : Form { public Form1() { InitializeComponent(); button2.DataBindings.Add("Enabled", button1, "Enabled"); button3.DataBindings.Add("Enabled", button1, "Enabled"); } private void ToggleEnableButton_Click(object sender, EventArgs e) { button1.Enabled = !button1.Enabled; } } }
Or another option, if some of the buttons are on the form while others are in a panel or group box the following stores buttons in this case ending with a digit (or use other logic to determine which buttons in the list are to be targeted e.g. set the Tag property to a value and work off that value).
Keep in mind that the where condition here is based off your example but as mentioned above can be any logic you see fit.
Form code
using System; using System.Collections.Generic; using System.Windows.Forms; namespace Demo { public partial class Form1 : Form { private readonly List<Button> _buttonsList; public Form1() { InitializeComponent(); _buttonsList = this.Buttons(); } private void ToggleEnableButton_Click(object sender, EventArgs e) { _buttonsList.ToggleEnableState(); } } }
Helpers
using System.Collections.Generic; using System.Linq; using System.Windows.Forms; namespace Demo { static class ControlExtensions { /// <summary> /// Get all buttons on a control/form or container /// </summary> /// <param name="control">form or container</param> /// <returns>list of buttons</returns> public static List<Button> ButtonList(this Control control) => control.Descendants<Button>().ToList(); /// <summary> /// Get all buttons in a list of buttons where the button name ends with a digit /// </summary> /// <param name="sender"></param> /// <returns></returns> public static List<Button> Buttons(this Control sender) => sender.ButtonList().Where(button => char.IsDigit(button.Name[button.Name.Length - 1])).ToList(); /// <summary> /// Toggle the state of the buttons enabled property /// </summary> /// <param name="sender">form or container</param> public static void ToggleEnableState(this List<Button> sender) { foreach (var button in sender) { button.Enabled = !button.Enabled; } } /// <summary> /// Set enable property /// </summary> /// <param name="sender">form or container</param> /// <param name="enabled">true or false</param> public static void SetEnableState(this List<Button> sender, bool enabled) { foreach (var button in sender) { button.Enabled = enabled; } } public static IEnumerable<T> Descendants<T>(this Control control) where T : class { foreach (Control child in control.Controls) { T thisControl = child as T; if (thisControl != null) { yield return (T)thisControl; } if (child.HasChildren) { foreach (T descendant in Descendants<T>(child)) { yield return descendant; } } } } } }
Paneland disable the panel (all the children of the panel will get disabled too.)