[英]How to put multiple textbox value into an array by a for loop
I got several textbox object on designer interface, let's say txtF1_ZHTW, txtF2_ZHTW, txtF3_ZHTW. 我在设计器界面上有几个文本框对象,比方说txtF1_ZHTW,txtF2_ZHTW,txtF3_ZHTW。
How to put the value of this 3 textbox into an array by a for loop? 如何通过for循环将此3文本框的值放入数组中?
The syntax I used for now is the worst way: 我现在使用的语法是最糟糕的方法:
fieldName_TW[0] = txtF1_ZHTW.Text;
fieldName_TW[1] = txtF2_ZHTW.Text;
For what I want to proceed is something like... 对于我想要继续的事情,类似...
for(i=0;i<3;i++)
{
fieldName_TW[i] = txtF[i+1]_ZHTW.Text;
}
So, how can I modify the code to use a for loop to enter the value of multiple textbox to an array? 因此,如何修改代码以使用for循环将多个文本框的值输入数组?
Put your textboxes in a collection, such as a List<TextBox>
, so you can iterate it. 将您的文本框放在一个集合中,例如
List<TextBox>
,以便可以对其进行迭代。
var texboxes = new List<TextBox>()
{
txtF1_ZHTW,
txtF2_ZHTW
};
// ...
foreach(var textbox in textboxes) // Assumes that fieldName_TW is large enough
fieldName_TW[i] = textbox.Text
I wouldn't rely on a name to make that kind of loop. 我不会依赖名称来进行这种循环。 Make a collection of your textboxes and add them in the right order, so you can use correct indexes to read them:
收集文本框并以正确的顺序添加它们,以便可以使用正确的索引来读取它们:
List<TextBox> textBoxes = new List<TextBox>() { txtF1_ZHTW, txtF2_ZHTW, txtF3_ZHTW };
Use the for-loop you already showed: 使用您已经显示的for循环:
for(int i=0; i < textBoxes.Count; i++)
{
fieldName_TW[i] = textBoxes[i].Text;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.