Anjola
Anjola

Reputation: 347

How to clear a textbox once a button is clicked in WPF?

How can I clear a textbox once a button is clicked in the WPF application, I know I have to do it in click method of the button but what code should I use for the mentioned purpose?

Upvotes: 23

Views: 283820

Answers (8)

Tomáš Oplatek
Tomáš Oplatek

Reputation: 360

There is one possible pitfall with using textBoxName.Text = string.Empty; and that is if you are using Text binding for your TextBox (i.e. <TextBox Text="{Binding Path=Description}"></TextBox>). In this case, setting an empty string will actually override and break your binding.

To prevent this behavior you have to use the Clear method:

textBoxName.Clear();

This way the TextBox will be cleared, but the binding will be kept intact.

Upvotes: 6

user2646464
user2646464

Reputation:

I use this. I think this is the simpliest way to do it:

 textBoxName.Clear();

Upvotes: 14

Farhan Aslam
Farhan Aslam

Reputation: 61

You can use Any of the statement given below to clear the text of the text box on button click:

  1. textBoxName.Text = string.Empty;
  2. textBoxName.Clear();
  3. textBoxName.Text = "";

Upvotes: 6

Nio74
Nio74

Reputation: 41

For me texBoxName.Clear();is the best method because I have textboxs in binding and if I use other methods I do not have a good day

Upvotes: 1

Er. Harry Singh
Er. Harry Singh

Reputation: 69

When you run your form and you want showing text in textbox is clear so you put the code : -

textBox1.text = String.Empty;

Where textBox1 is your textbox name.

Upvotes: 0

misak
misak

Reputation: 342

For example:

XAML:

<Button Content="ok" Click="Button_Click"/>
<TextBlock Name="textBoxName"/>

In code:

 private void Button_Click(object sender, RoutedEventArgs e)
{
textBoxName.Text = "";
}

Upvotes: 6

devdigital
devdigital

Reputation: 34349

You wouldn't have to put it in the button click hander. If you were, then you'd assign your text box a name (x:Name) in your view and then use the generated member of the same name in the code behind to set the Text property.

If you were avoiding code behind, then you would investigate the MVVM design pattern and data binding, and bind a property on your view model to the text box's Text property.

Upvotes: 3

ChrisO
ChrisO

Reputation: 5465

Give your textbox a name and then use TextBoxName.Text = String.Empty;

Upvotes: 46

Related Questions