I am creating a TextBox
and a Button
dynamically using the following code:
Button btnClickMe = new Button();
btnClickMe.Content = "Click Me";
btnClickMe.Name = "btnClickMe";
btnClickMe.Click += new RoutedEventHandler(this.CallMeClick);
someStackPanel.Childern.Add(btnClickMe);
TextBox txtNumber = new TextBox();
txtNumber.Name = "txtNumber";
txtNumber.Text = "1776";
someStackPanel.Childern.Add(txtNumber);
I hook up to a click event to the Click Me
button. The click me button even is fired correctly. However I cannot find the TextBox
I entered dynamically.
Here is my click me event:
protected void ClickMeClick(object sender, RoutedEventArgs e)
{
// Find the phone number
TextBox txtNumber = this.someStackPanel.FindName("txtNumber") as TextBox;
if (txtNumber != null)
{
string message = string.Format("The number is {0}", txtNumber.Text);
MessageBox.Show(message);
}
else
{
MessageBox.Show("Textbox is null");
}
}
How can I find the TextBox
txtNumber
?
If you want to do a comprehensive search through the visual tree of controls, you can use the VisualTreeHelper class.
Use the following code to iterate through all of the visual children of a control:
If you want to search down into the tree, you will want to perform this loop recursively, like so:
Josh G had the clue that fixed this code: use RegisterName().
Three benefits here:
Complete code.
Is there any way you can make the TextBox control a field in your class instead of a variable inside your generator method
You can get your original click handler to work by registering the name of the text box:
This will then allow you to call FindName on the StackPanel and find the TextBox.
Another method is to set the associated
TextBox
asButton Tag
when instanciating them.This way you can retrieve it back in event handler.