Reputation: 34158
I have a WPF application with a Grid
where there are multiple TextBox
s. How I can make every TextBox.Text = null;
with a button click?
Upvotes: 4
Views: 2423
Reputation: 64068
There are multiple approaches to this problem.
The first is a hybrid approach where you would have the data flow down to your text boxes through bindings and a button click remove the data.
To start with you need to make sure your data classes implement INotifyPropertyChanged
:
public class Foo : INotifyPropertyChanged
{
private string bar;
private string baz;
public string Bar
{
get { return this.bar; }
set
{
this.bar = value;
// this is where the magic of bindings happens
this.OnPropertyChanged("Bar");
}
}
// rest of the class here...
}
Referenced in your XAML through bindings:
<Grid>
<Grid.RowDefinitions>
<!-- ... -->
</Grid.RowDefinitions>
<TextBox Grid.Row="0"
Text="{Binding Bar}" />
<TextBox Grid.Row="1"
Text="{Binding Baz}" />
<!-- A more complete example would use Button.Command -->
<Button Grid.Row="2"
Content="CLEAR"
Click="ClearButton_Click" />
Finally, these bindings are wired up using the DataContext
and a routed event handler in your Window
s code-behind:
public Window1()
{
this.InitializeComponent();
// sets up the DataContext used by the bindings
this.Clear();
}
private void ClearButton_Click(object sender, RoutedEventArgs e)
{
this.Clear();
}
private void Clear()
{
this.DataContext = new Foo();
}
This approach will push you in a better direction to handle more complicated UI's.
A last ditch effort would be:
/// <summary>This is a bad choice.</summary>
private void ClearButton_Click(object sender, RoutedEventArgs e)
{
// assumes the Grid is named MyGrid
foreach (var textBox in this.MyGrid.Children.OfType<TextBox>())
{
textBox.Text = null;
}
}
Upvotes: 1
Reputation: 76929
The code Tom and CodeNaked gave will do what you want, but I would generally advise against this logic.
The Grid is there to help you organize your controls visually, it's a layout container. By no means it should be used to organize your controls logically, behind the scenes.
As I said, though, this is quite general advise. Your program might benefit from the other approach.
Upvotes: 1
Reputation: 41393
Something like this would work:
private void Button_Click(object sender, RoutedEventArgs e) {
foreach (UIElement element in this.grid.Children) {
TextBox textBox = element as TextBox;
if (textBox == null)
continue;
textBox.Text = null;
}
}
Upvotes: 3
Reputation: 10452
Give this a try:
private void button1_Click(object sender, RoutedEventArgs e)
{
foreach (UIElement control in myGrid.Children)
{
if (control.GetType() == typeof(TextBox))
{
TextBox txtBox = (TextBox)control;
txtBox.Text = null;
}
}
}
Upvotes: 4