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.

11 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.

      • GodlessGeek says:

        Oops, you’re right. My apologies. I haven’t used Forms in a long time, preferring WPF. Sometimes I forget there are differences.

  2. Alan says:

    Does this make it possible to address the items numerically, as with a standard array? Something like:

    Int ArrAttr = 2;
    BreakfastControls[ArrAttr].IsChecked ^= true;
    //toggles chkOrangeJuice

    • RodStephens says:

      Sure. Just put the controls in the array in the order in which you want to use them.

      • Alan says:

        Thank you for your response.

      • Alan says:
        //X, Y, Z are labels on From1.
        namespace ArrayOfControls
            public partial class Form1 : Form
                public Form1()
                private Label[] labarray;
                public void Form1_Load(object sender, EventArgs e)
                    labarray = new Label[]
                        { X, Y, Z };            
                private void button1_Click(object sender, EventArgs e)
                    labarray[1].Visible ^= true;

        on click, exits with
        “System.NullReferenceException: ‘Object reference not set to an instance of an object.’ labarray was null.”

        Apologies for leaning on you here, and I know the dumb is on my side of the keyboard. I’m new to C#. What am I doing wrong?

        • RodStephens says:

          Sorry but I don’t know what’s wrong. When I copy and paste that code into a new project, it works.

          The only thing I can think of offhand is if the Form’s Load event isn’t actually attached to the Form_Load event handler. To check, open the Form Designer and click on the form. In the Properties window, click the Events icon (the little lightning bolt). Then see of the Load event is attached to Form_Load. If it is not, click the dropdown and select it.

          • Alan says:

            Nailed it.

            I’ve been trying for a while to figure out how to address controls numerically. Being able to address these by index is going to help me clean up a particularly ugly method involving toggling the visibility of 12 labels based on a 1:1 relationship with a boolean array.

            Better still I might be able to eliminate the boolean array altogether, and perform my offset math based on the states in the control array.

            Thank you for your time and patience.

  3. Richardson says:

    advantages of using control arrays in visual basic programming?

    • RodStephens says:

      Mostly it lets you access the arrays by their indices. For example, if you want to clear a whole bunch of textboxes at the same time, you can just loop through the array.

      Of you might have a series of related controls. For example, 10 textboxes lined up with 10 checkboxes and 10 buttons. You could put each kind of control in a separate array and then work with them together. For example, the controls textboxes[i], checkboxees[i], and buttons[i] would go together.

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.