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.

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

Arrays of controls such as this can be extremely useful, particularly if you need to manipulate a lot of controls at once.

   

 

What did you think of this article?




Trackbacks
  • No trackbacks exist for this post.
Comments
  • No comments exist for this post.
Leave a comment

Submitted comments are subject to moderation before being displayed.

 Name

 Email (will not be published)

 Website

Your comment is 0 characters limited to 3000 characters.