0

I've some texBox where the users has to input some data.

textBox1
textBox2
textBox3
textBox4

After filling those textBox, the users presses on a button and other stuff is done.

I want to clear all the textBox as soon as the users clicks on the button.

I know I can do it by one by one using .clear

textBox1.clear();
textBox2.clear();
textBox3.clear();
textBox4.clear();

But this looks a bit dirty for me as I have more than 4 textBoxes.

So I was thinking about looping from 1 to number_of_textboxes and then .clean each one, but I dont know how can I get the number_of_texboxes. Is there a way to get it so I can make this loop, or any other easy way to achieve this?

Thanks in advance.

Avión
  • 7,963
  • 11
  • 64
  • 105
  • You can use the helper method from the answers [here](http://stackoverflow.com/questions/974598/find-all-controls-in-wpf-window-by-type). Assuming you want to clear all the textbox from a specific parent (i.e. window), you can call it like foreach (TextBox textbox in FindVisualChildren(parentWindow)) { // TODO: Clear textbox } – cubski May 12 '15 at 12:38

2 Answers2

2

You can iterate through all of the elements in the UI and extract just the Textboxes, but it's hardly efficient, compared with your direct code. However, you could do that with a recursive method using the VisualTreeHelper class, like this:

GetChildrenOfType<TextBox>(this).ToList().ForEach(textBox => textBox.Clear());

...

public static IEnumerable<T> GetChildrenOfType<T>(DependencyObject dependencyObject) where T : DependencyObject
{
    if (dependencyObject != null)
    {
        for (int index = 0; index < VisualTreeHelper.GetChildrenCount(dependencyObject); index++)
        {
            DependencyObject child = VisualTreeHelper.GetChild(dependencyObject, index);
            if (child != null && child is T) yield return (T)child;
            foreach (T childOfChild in GetChildrenOfType<T>(child)) yield return childOfChild;
        }
    }
}

This of course assumes that this is the parent control of the relevant TextBoxes... if not, you could call something like this:

GetChildrenOfType<TextBox>(ParentGrid).ToList().ForEach(textBox => textBox.Clear());
Sheridan
  • 68,826
  • 24
  • 143
  • 183
1

Somewhat similar as Sheridan says:

 void ClearAllTextBoxes(DependencyObject obj)
    {
        for (int i = 0; i < VisualTreeHelper.GetChildrenCount(obj); i++)
        {
            if (obj is TextBox)
                ((TextBox)obj).Text = null;
            LoopVisualTree(VisualTreeHelper.GetChild(obj, i));
        }
    }

However for WPF it's often better to clear out the objects to which the textboxes are bound. This makes sure your logic isn't dependent on a UI implementation.

Thomas Bouman
  • 608
  • 4
  • 17