动态创建多个文本框C#

本文关键字:文本 创建 动态 | 更新日期: 2023-09-27 18:25:25

这是我的代码。但我所有的文本框的值都是空的。

    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++;
        }
    }

谢谢你的帮助。

动态创建多个文本框C#

数组创建调用只是将元素初始化为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中。例如CCD_ 4。

您需要在循环开始时初始化您的文本框。

您还需要使用for循环而不是foreach。

您需要更新TextBoxes:

for (int i = 0; i < teams; i++)
{
    txtTeamNames[i] = new TextBox();
    ...
}

如果你做得不对,你必须将文本框实例添加到数组中,然后将其添加到表单中。这就是你应该做的。

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++;
            }
        }
    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");   
        }
    }