How to iterate all textboxes on current page
c#, windows-8, windows-store-apps, winrt-xaml
Solution
This is how you do what you want.
public MainPage()
{
this.InitializeComponent();
Loaded += MainPage_Loaded;
}
void MainPage_Loaded(object sender, RoutedEventArgs e)
{
foreach (var textBox in AllTextBoxes(this))
{
textBox.Text = "Hello world";
}
}
List<TextBox> AllTextBoxes(DependencyObject parent)
{
var list = new List<TextBox>();
for (int i = 0; i < VisualTreeHelper.GetChildrenCount(parent); i++)
{
var child = VisualTreeHelper.GetChild(parent, i);
if (child is TextBox)
list.Add(child as TextBox);
list.AddRange(AllTextBoxes(child));
}
return list;
}
Reference: http://blog.jerrynixon.com/2012/09/how-to-access-named-control-inside-xaml.html
Best of luck!
Problem
say I have added many textboxes. How to iterate or loop thru all the textboxes and do some checking. Check if each textbox's content is a number. Below is the code for winForm, how to do in in WinRT? ``` foreach (Control item in GroupBox1.Controls) { if (item.GetType() == typeof(TextBox)) { if (string.IsNullOrEmpty( ((TextBox)item).Text)) { //Empty text in this box } } } ``` Thanks.