[C# Helper]
Index Books FAQ Contact About Rod
[Beginning Database Design Solutions, Second Edition]

[Beginning Software Engineering, Second Edition]

[Essential Algorithms, Second Edition]

[The Modern C# Challenge]

[WPF 3d, Three-Dimensional Graphics with WPF and C#]

[The C# Helper Top 100]

[Interview Puzzles Dissected]

[C# 24-Hour Trainer]

[C# 5.0 Programmer's Reference]

[MCSD Certification Toolkit (Exam 70-483): Programming in C#]

Title: control array

[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 the example to experiment with it and to see additional details.

© 2009-2023 Rocky Mountain Computer Consulting, Inc. All rights reserved.