Title: 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)
foreach (Control control in Controls)
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)
foreach (Button btn in Controls.OfType<Button>())
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)
foreach (ScrollBar sbar in Controls.OfType<ScrollBar>())
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.