Many form-TextBox' in one List<TextBox>

血红的双手。 提交于 2020-01-04 15:14:09

问题


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

}


来源:https://stackoverflow.com/questions/15797447/many-form-textbox-in-one-listtextbox

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!