Avión
Avión

Reputation: 8386

WPF - Clear all textBox via code after pressing a button

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.

Upvotes: 0

Views: 1216

Answers (2)

Thomas Bouman
Thomas Bouman

Reputation: 608

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.

Upvotes: 1

Sheridan
Sheridan

Reputation: 69959

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

Upvotes: 2

Related Questions