Recursion method to clear TextBoxes in nested Container Controls
In this post; I will try to explain use of Recursion method to clear TextBoxes in nested Container Controls.
Below is the Iterative code snippet to clear TextBoxes within any Container Control:
foreach (Control ctl in this.Controls)
{
if (ctl is TextBox)
ctl.Text = String.Empty;
}
This code works fine until you insert further / nested GroupBoxes (or any) containers and move the textbox controls into them.
The Controls collection of the form or any other container contains only direct child controls. The contents of nested container controls are not included.
Recursion is the best technique to access a logical tree of unknown depth:
public static void ClearTextboxes(Control container)
{ foreach (Control ctl in container.Controls)
{ var textBox = ctl as TextBox;
if (textBox != null)
{ textBox.Text = String.Empty; }
if (ctl.Controls.Count > 0)
{ ClearTextboxes(ctl); }
}
}