This is a snippet that will get either all the child controls of a form (other other control) or controls of a specified type. This is for C# 4.0 as it utilizes an optional parameter.

1,409 Views
/// <summary>
/// method to get all child & sub-child controls within a control by type
/// </summary>
/// <param name="control">the control we're searching in (use this for the form)</param>
/// <param name="type">The control type we're looking for (i.e; TextBox)</param>
/// <returns></returns>
public IEnumerable<Control> GetAll(Control control, Type type = null)
{
    var controls = control.Controls.Cast<Control>();

    //check the all value, if true then get all the controls
    //otherwise get the controls of the specified type
    if (type==null)
        return controls.SelectMany(ctrl => GetAll(ctrl, type)).Concat(controls);
    else
        return controls.SelectMany(ctrl => GetAll(ctrl, type)).Concat(controls).Where(c => c.GetType() == type);
}

//Sample usage for getting all controls
private void Form1_Load(object sender, EventArgs e)
{
    var c = GetAll(this);
    MessageBox.Show("Total Controls: " + c.Count());
}

//Sample usage for getting controls of a specific type
private void Form1_Load(object sender, EventArgs e)
{
    var c = GetAll(this, typeof(TextBox));
    MessageBox.Show("Total Controls: " + c.Count());
}
About the Author

I have been a professional programmer for a bit over 15 years now (more than that if you could school time and such), focusing mainly on Microsoft technologies for the past 7 years (Mainly C#, it's such a beautiful language).

I am a die hard programmer, I live, eat, sleep &amp; breath code and cannot ever see myself doing anything but this.