Many form-TextBox' in one List

2019-07-18 19:44发布

问题:

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... :)

回答1:

If it's WinForms this should work...

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


回答2:

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));


回答3:

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

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

}


标签: c# list textbox