Use a control array in C#

[control array]

Sometimes it may be handy to use a control array. Way back before .NET, Visual Basic let you define control arrays at design time. The concept disappeared in .NET, but they can still be useful if you need to perform the same operation on a group of controls. For example, you could loop through a control array to clear a collection of TextBoxes or CheckBoxes. In cases like those, you can make an array containing references to the controls and then iterate over the array.

This example uses three arrays of CheckBox controls 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.

// Reset the breakfast controls.
private void btnResetBreakfast_Click(object sender, EventArgs e)
{
    foreach (CheckBox chk in BreakfastControls)
    {
        chk.Checked = false;
    }
}

Control arrays such as these can be extremely useful, particularly if you need to manipulate a lot of controls all at the same time.


Download Example   Follow me on Twitter   RSS feed   Donate




This entry was posted in arrays, classes, syntax and tagged , , , , , , , , , . Bookmark the permalink.

2 Responses to Use a control array in C#

  1. GodlessGeek says:

    Instead of “chk.Checked = false;”, it should be “chk.IsChecked = false;” Checked is an event, not a property. IsChecked is the bool {get; set;} property for a CheckBox.

    foreach (CheckBox chk in BreakfastControls)
    {
        chk.IsChecked = false;
    }

    • RodStephens says:

      Actually that’s not true. This is a Windows Forms example and in Windows Forms, Checked is a boolean property and CheckedChanged is the event. (If that were not true, the example wouldn’t work.)

      In WPF, IsChecked is the property. If you rewrite the example in WPF, you need to use IsChecked.

Leave a Reply

Your email address will not be published. Required fields are marked *