Nick Peelman
Nick Peelman

Reputation: 583

Many form-TextBox' in one List<TextBox>

I've got a form with 20 TextBoxes(2-22) and I would like to add them all the a List<TextBox> So I can add the same text for example in all of them using the for-statement.

What I thought(Lol.):

List<TextBox> textBoxes = new List<TextBox>();

for(int i = 2; i < 23; i++) {

//This String should refer to = textBox2, textBox3, etc
textBoxes.Add("textBox"+ Convert.ToString(i));

}

But this won't work because It can't convert a string to a textBoxName. You can do this:

  textBoxes.Add(textBox2);
  textBoxes.Add(textBox3);
  textBoxes.Add(textBox4);
  ...So on

But ain't nobody got time for that... :)

Upvotes: 2

Views: 6609

Answers (3)

Tanner
Tanner

Reputation: 22743

You need to cast them as controls before passing them into your list rather than trying to put a string value in your List<TextBox>.

Try adding this into your loop instead:

textBoxes.Add((TextBox)this.Controls.Find("textBox"+ Convert.ToString(i),true));

Upvotes: 1

Ceres
Ceres

Reputation: 3668

List<TextBox> textBoxes = new List<TextBox>();

for (int i = 1; i <= 22; i++) {
    textBoxes.Add((TextBox)this.Controls.Find("textBox" + i, false)(0));

}

Upvotes: 0

Jens Granlund
Jens Granlund

Reputation: 5070

If it's WinForms this should work...

textBoxes.Add((TextBox)Controls.Find("textBox" + i, true)[0]);

Upvotes: 2

Related Questions