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

Comments

# Recursion method to clear TextBoxes in nested Container Controls « KaushaL.NET

Pingback from  Recursion method to clear TextBoxes in nested Container Controls « KaushaL.NET

# re: Recursion method to clear TextBoxes in nested Container Controls

Wednesday, September 02, 2009 9:28 PM by donsgal

Bravo, it's a great idea

# re: Recursion method to clear TextBoxes in nested Container Controls

Wednesday, October 14, 2009 8:18 PM by Polprav

Hello from Russia)