Search code examples
c#wpftextbox

changing multiple textboxes at once


In my program i have 50 text boxes with the name TB1 to TB50

I am trying to use a for loop to change the content of them all with a few lines of code. Instead of repeating the code 50 times. However i cant get this to work. Any help would be greatly appreciated (Please see what where i got ot below)

private void Button_Click(object sender, RoutedEventArgs e)
{
    for (int i =1; i < 50; i++)
    {
        string TB = "TB" + i;

        TextBox TBN = new TextBox();

        TBN.Name = TB;
        TBN.Text = "Textbox Changed";
    }

Solution

  • first get all textboxes of some element depending where your textboxes are, for example if they are in gird just replace rootControl with name of your grid, after that it's lemon squeezy, using this approach textbox name doesn't matter.

    IEnumerable<TextBox> TextboxCollection = rootControl.Children.OfType<TextBox>();
                foreach(TextBox tb in TextboxCollection)
                {
                    tb.Text = "Text";
                }