Many form-TextBox' in one List

2019-07-18 19:53发布

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

标签: c# list textbox
3条回答
叼着烟拽天下
2楼-- · 2019-07-18 20:08

If it's WinForms this should work...

textBoxes.Add((TextBox)Controls.Find("textBox" + i, true)[0]);
查看更多
对你真心纯属浪费
3楼-- · 2019-07-18 20:09

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));
查看更多
【Aperson】
4楼-- · 2019-07-18 20:24
List<TextBox> textBoxes = new List<TextBox>();

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

}
查看更多
登录 后发表回答