[C# Helper]
Index Books FAQ Contact About Rod
[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]

[Beginning Software Engineering]

[C# 5.0 Programmer's Reference]

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

Title: Loop over a form's controls in C#

[Loop over a form's controls in C#]

This example shows how to loop over controls of various types on a form.

The Control class defines a Controls property that is a collection containing references to the controls inside a control. For example, a form's Controls collection holds references to the controls on the form.

Note that the collection only holds controls directly contained in the parent. For example, suppose a form contains a Panel and the Panel contains a PictureBox. Then the Panel is in the form's Controls collection but the PictureBox is not. in that case, the PictureBox is contained in the Panel control's collection.

Looping through the Controls collection is easy. For example, when you click this program's All button, the following code loops through all of the form's controls.

private void btnAll_Click(object sender, EventArgs e) { lstControls.Items.Clear(); foreach (Control control in Controls) lstControls.Items.Add(control.Name); }

This code clears the program's ListBox and then loops through the form's controls, adding their names to the ListBox.

That much is easy. What many don't realize is that Controls collection has a generic OfType method that filters the collection and returns an IEnumerable containing the objects that match a particular type.

For example, when you click the program's Button button, the following code executes.

private void btnButton_Click(object sender, EventArgs e) { lstControls.Items.Clear(); foreach (Button btn in Controls.OfType<Button>()) lstControls.Items.Add(btn.Name); }

This code clears the program's ListBox. It then uses the Controls collection's OfType method to loop through the form's Button controls, adding their names to the ListBox.

The OfType method selects controls that can be converted into the type that you specify. For example, when you click the ScrollBar button, the following code executes.

private void btnScrollBar_Click(object sender, EventArgs e) { lstControls.Items.Clear(); foreach (ScrollBar sbar in Controls.OfType<ScrollBar>()) lstControls.Items.Add(sbar.Name); }

This code selects ScrollBar objects. Because the HScrollBar and VScrollBar controls both inherit from ScrollBar, this code selects both of the program's scroll bars.

Download the example to experiment with it and to see additional details.

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