Code :: Get Controls Recursively

Returns the list of controls in a form irrespective of the container it has.

(extensibility possible to web forms as well)

private IList<Control> _controlsList = new List<Control>();

public IEnumerable<Control> GetControlsRecursively(Control container)
{
_controlsList.Clear();
FindControlsRecursively(container);

return _controlsList;
}

private void FindControlsRecursively(Control container)
{
foreach (Control control in container.Controls)
{
_controlsList.Add(control);
if (container.HasChildren)
FindControlsRecursively(control);
}
}

Leave a Reply

Your email address will not be published. Required fields are marked *