How to clear a textbox once a button is clicked in WPF?
Solution 1
Give your textbox a name and then use TextBoxName.Text = String.Empty;
Solution 2
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.
Solution 3
For example:
XAML:
<Button Content="ok" Click="Button_Click"/>
<TextBlock Name="textBoxName"/>
In code:
private void Button_Click(object sender, RoutedEventArgs e)
{
textBoxName.Text = "";
}
Solution 4
You can use Any of the statement given below to clear the text of the text box on button click:
textBoxName.Text = string.Empty;
textBoxName.Clear();
textBoxName.Text = "";
Solution 5
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.
Anjola
Updated on January 11, 2020Comments
-
Anjola over 4 years
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? -
Sonhja about 11 yearsThis one is the good solution if you want to avoid
DataBindings
on WPF. -
T4NK3R over 7 yearsIntriguing - will investigate, as soon as I've finished the "native WPF" tutorial!
-
C.Champagne over 6 yearsWhat is the added value considering the accepted answer?
-
15ee8f99-57ff-4f92-890c-b56153 almost 5 yearsIf you’re using bindings properly, it might make more sense to set the viewmodel property to the empty string.