这是我的代码。 但是我的所有文本框的值都是空的。
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++;
}
}
感谢您的帮助。
答案 0 :(得分:9)
数组创建调用只是将元素初始化为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;
}
注意:正如有些人指出的那样,为了让这段代码有意义,您需要将每个TextBox
添加到父Control
答案 1 :(得分:1)
您需要在循环开始时初始化文本框。
您还需要使用for循环而不是foreach。
答案 2 :(得分:1)
您需要新建TextBoxes:
for (int i = 0; i < teams; i++)
{
txtTeamNames[i] = new TextBox();
...
}
答案 3 :(得分:0)
您做错了,您必须将文本框实例添加到数组中,然后将其添加到表单中。这就是你应该怎么做的。
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++;
}
}
答案 4 :(得分:0)
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");
}
}