[LINQ] Get child controls


using System.Collections.Generic ;
using System.Linq;
///
/// Get all child & sub-child controls within a control by type
///

/// The control we're searching in form/page.
/// The control type we're looking for (i.e; TextBox)
///
public IEnumerable < Control > GetAllChildControls(Control control, Type type = null)
{
var controls = control.Controls.Cast< Control >();

if (type == null)
return controls.SelectMany(ctrl => GetAllChildControls(ctrl, type)).Concat(controls);
else
return controls.SelectMany(ctrl => GetAllChildControls(ctrl, type)).Concat(controls).Where(c => c.GetType() == type);
}



//How to use.
IEnumerable< Control > textBoxControls = GetAllChildControls(this, typeof(TextBox));
IEnumerable< Control > allConrols = GetAllChildControls(this);


Reference : http://www.dreamincode.net/code/snippet5634.htm

沒有留言:

張貼留言