I liked this answer (https://mcmap.net/q/758960/-find-all-child-controls-of-specific-type-using-enumerable-oftype-lt-t-gt-or-linq) 12 years later and wanted to do what KeithS suggested and build in the option to pass in a type constraint to return only the type of controls you are after.
Extension Methods
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
namespace MyApp.Extensions
{
public static class ControlExtensions
{
public static IEnumerable<Control> FlattenChildren<T>(this Control control)
{
return control.FlattenChildren().OfType<T>().Cast<Control>();
}
public static IEnumerable<Control> FlattenChildren(this Control control)
{
var children = control.Controls.Cast<Control>();
return children.SelectMany(c => FlattenChildren(c)).Concat(children);
}
}
}
Example Usage
Added to the form's _Load
event...
//Show the name of each ComboBox on a form (even nested controls)
foreach (ComboBox cb in this.FlattenChildren<ComboBox>())
{
Debug.WriteLine(cb.Name);
}
//Get the number of controls on a form
Debug.WriteLine("Control count on form: " + this.FlattenChildren().Count());