Lizzy
Lizzy

Reputation: 2153

iterate text boxes by a for loop

Say I have 10 text boxes and I want to put the same text into each of them. I don't want to write textBoxNum. Text = "hello!" ten times so I might write something like this:

for(int i=1; i<=10; i++)
{
    textBox + i. Text = "hello!";
}

Obviously, it doesn't work.

How can this be done with a for loop ?

Upvotes: 2

Views: 6132

Answers (4)

WaterSoul
WaterSoul

Reputation: 387

You could also edit controls only matching something that you want. Here's an example.

foreach(Control ctrl in Controls)
  {
    if (ctrl.Name.StartsWith("TextBoxToEdit"))
    {
      ctrl.Text = "Hello!";
    }
  }

Also, there is no need to cast the control into TextBox as Control already has the Text property.

Upvotes: 0

Anthony Pegram
Anthony Pegram

Reputation: 126794

You either need to load all of your textboxes into a list or array structure, and this will allow you to iterate over it.

TextBox[] boxes = { tb1, tb2, tb3, ... };

Otherwise, you could inspect the Controls property of your form/container for items of the TextBox type. If the controls could be nested in deeper containers, you might need to recursively explore them (at this point, I would seriously consider an array approach, unless you have some ghastly number of textboxes to load). But as a starting point, you might have

foreach (var tb in this.Controls.OfType<TextBox>())
{
    tb.Text = "whatever";
}

Upvotes: 6

Iain Ward
Iain Ward

Reputation: 9936

Like this:

foreach (Control c  in this.Controls)
{
     if (c is TextBox)
     {
         ((TextBox)c).Text = "Hello";
     }
}

Assuming you want to set the text of all textboxes contained on the control\form, but can be modified for more specific scenarios

Upvotes: 1

SLaks
SLaks

Reputation: 887195

You should put your textboxes into an array:

TextBox[] boxes;

public MyForm() {
    InitializeComponent();
    boxes = { someTextBox, otherTextBox, ... };
}

Upvotes: 3

Related Questions