BLOG.CSHARPHELPER.COM: Make and use an array of controls in C#
Make and use an array of controls in C#
Sometimes you may need to perform the same operation on a group of controls. For example, clearing a series of TextBoxes or CheckBoxes. In cases like that, you can make an array containing references to the controls and then iterate over the array.
This example uses three arrays of CheckBoxes so it can easily uncheck the controls in each array. The following code shows how the program declares its arrays.
// Arrays of controls. private CheckBox[] BreakfastControls, LunchControls, DinnerControls;
The following code shows how the program initializes its arrays when the form loads.
// Initialize the arrays of controls. private void Form1_Load(object sender, EventArgs e) { BreakfastControls = new CheckBox[] { chkCereal, chkToast, chkOrangeJuice }; LunchControls = new CheckBox[] { chkSandwhich, chkChips, chkSoda }; DinnerControls = new CheckBox[] { chkSalad, chkTofuburger, chkWine }; }
When you click one of the reset buttons, code similar to the following executes to clear the CheckBoxes in the corresponding array.
Comments