动态创建多个文本框 C#
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9368748/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
dynamically create multiple textboxes C#
提问by lajtmaN
This is my code. But all my textboxes's value is just null.
这是我的代码。但是我所有的文本框的值都是空的。
public void createTxtTeamNames()
{
TextBox[] txtTeamNames = new TextBox[teams];
int i = 0;
foreach (TextBox txt in txtTeamNames)
{
string name = "TeamNumber" + i.ToString();
txt.Name = name;
txt.Text = name;
txt.Location = new Point(172, 32 + (i * 28));
txt.Visible = true;
i++;
}
}
Thanks for the help.
谢谢您的帮助。
采纳答案by JaredPar
The array creation call just initializes the elements to null. You need to individually create them.
数组创建调用只是将元素初始化为null。您需要单独创建它们。
TextBox[] txtTeamNames = new TextBox[teams];
for (int i = 0; i < txtTeamNames.Length; i++) {
var txt = new TextBox();
txtTeamNames[i] = txt;
txt.Name = name;
txt.Text = name;
txt.Location = new Point(172, 32 + (i * 28));
txt.Visible = true;
}
Note: As several people have pointed out in order for this code to be meaningful you will need to add each TextBoxto a parent Control. eg this.Controls.Add(txt).
注意:正如一些人所指出的,为了使此代码有意义,您需要将每个添加TextBox到 parent Control。例如this.Controls.Add(txt)。
回答by Panetta
You need to initialize your textbox at the start of the loop.
您需要在循环开始时初始化文本框。
You also need to use a for loop instead of a foreach.
您还需要使用 for 循环而不是 foreach。
回答by Steve Czetty
You need to new up your TextBoxes:
你需要更新你的文本框:
for (int i = 0; i < teams; i++)
{
txtTeamNames[i] = new TextBox();
...
}
回答by Senad Me?kin
You are doing it wrong, you have to add textbox instances to the array, and then add it to the form. This is how you should do it.
您做错了,您必须将文本框实例添加到数组中,然后将其添加到表单中。这就是你应该做的。
public void createTxtTeamNames()
{
TextBox[] txtTeamNames = new TextBox[10];
for (int u = 0; u < txtTeamNames.Count(); u++)
{
txtTeamNames[u] = new TextBox();
}
int i = 0;
foreach (TextBox txt in txtTeamNames)
{
string name = "TeamNumber" + i.ToString();
txt.Name = name;
txt.Text = name;
txt.Location = new Point(0, 32 + (i * 28));
txt.Visible = true;
this.Controls.Add(txt);
i++;
}
}
回答by user4819434
private void button2_Click(object sender, EventArgs e)
{
TextBox tb = new TextBox();
tb.Name = abc;
tb.Text = "" + i;
Point p = new Point(20 + i, 30 * i);
tb.Location = p;
this.Controls.Add(tb);
i++;
}
private void button3_Click(object sender, EventArgs e)
{
foreach (TextBox item in this.Controls.OfType<TextBox>())
{
MessageBox.Show(item.Name + ": " + item.Text + "\n");
}
}

