Get child controls of form or other control (C# 4.0)

PsychoCoder 0 Tallied Votes 3K Views Share

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.

/// <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());
}