Search code examples
c#wpfvisual-studiotextbox

How to I grab the text of numbered Textboxes dynamically in WPF?


I am creating a contacts add and I want to add the option to add more than 1 phone numbers. I allow the creation of more textboxes for the user to add number with this button:

        private void AddPhoneNumberButton_Click(object sender, RoutedEventArgs e)
        {
            int numberOfTextBoxes = PhoneNumberStackPanel.Children.OfType<TextBox>().Count();

            TextBox txtbox = new TextBox();
            txtbox.Name = $"PhoneNumberTextBox{numberOfTextBoxes}";
            txtbox.Width = 200;
            txtbox.Background = Brushes.White;
            txtbox.Margin = new Thickness(0,10,0,0);
            PhoneNumberStackPanel.Children.Add(txtbox);
        }

Now how to I refer to those textboxes dynamically. Like if I want to grab all the text in these textboxes with this loop:

for ( int i = 0 ; i < PhoneNumberStackPanel.Children.OfType<TextBox>().Count() ; i++){}

Solution

  • use foreach loop:

    foreach(TextBox tb in PhoneNumberStackPanel.Children.OfType<TextBox>())
    {
        string text = tb.Text;
    }
    

    also consider replacing StackPanel with ItemsControl:

    private void AddPhoneNumberButton_Click(object sender, RoutedEventArgs e)
    {
        int numberOfTextBoxes = PhoneNumberItemsControl.Items.Count;
    
        TextBox txtbox = new TextBox();
        txtbox.Name = $"PhoneNumberTextBox{numberOfTextBoxes}";
        txtbox.Width = 200;
        txtbox.Background = Brushes.White;
        txtbox.Margin = new Thickness(0,10,0,0);
        PhoneNumberItemsControl.Items.Add(txtbox);
    }
    
    foreach(TextBox tb in PhoneNumberItemsControl.Items.OfType<TextBox>())
    {
    }
    

    next step which you can make is moving TextBoxes into ItemsControl.ItemTemplate. (it becomes a "must-do" as soon as you need visual structure more complex than a single element)