How to recursively get all controls on a form in C#
You usually use the Controls property of a form to get a collection of the controls on a form but this does not always work. If you have controls like GroupBoxes with controls inside them then the Controls property will not contain any of the child controls.
It is clear that the problem involves a hierarchy which often means that you will need to use recursion to solve the problem.
We need to create a function called GetAllControls(). The function will return a List of type Control. It will take an IList as a parameter. IList is used because the Controls property of a form is of type ControlCollection and we are using the List type to return the values and both List and ControlCollection are ILists. The function will use the standard recursion format that most recursive functions use. Here is the function:
public static List<Control> GetAllControls(IList ctrls)
{
List<Control> RetCtrls = new List<Control>();
foreach (Control ctl in ctrls)
{
RetCtrls.Add(ctl);
List<Control> SubCtrls = GetAllControls(ctl.Controls);
RetCtrls.AddRange(SubCtrls);
}
return RetCtrls;
}
To use this function we must pass Form.Controls as the parameter and assign the result to a List of type Control. Here is how to use it:
List<Control> lstControls = GetAllControls(MyForm.Controls);