动态创建标签和文本框

时间:2018-02-26 18:12:09

标签: c#

仅生成1个文本框字段和标签。我的计划是在1个面板中只生成4个字段

private void btnAdd_Click(object sender, EventArgs e)
{
    Label label = new Label();
    int count = panel1.Controls.OfType<Label>().ToList().Count;
    label.Location = new Point(10, (25 * count) + 2);
    label.Size = new Size(40, 20);
    label.Top = 4;
    label.ForeColor = System.Drawing.Color.White;
    label.Name = "label_" + (count + 1);
    label.Text = "Field " + (count + 1);
    panel3.Controls.Add(label);

    TextBox textbox = new TextBox();
    count = panel1.Controls.OfType<TextBox>().ToList().Count;
    textbox.Location = new Point(60, 25 * count);
    textbox.Top = 4;
    textbox.Size = new Size(301, 20);
    textbox.Name = "textbox_" + (count + 1);
    textbox.TextChanged += new System.EventHandler(this.TextBox_Changed);
    panel3.Controls.Add(textbox);
}

1 个答案:

答案 0 :(得分:2)

您可以使用for循环同时添加多个文本框和标签,并且必须删除textbox.Top = 4;,因为覆盖label.Location = new Point(10, (25 * count) + 2);和所有控件都具有相同的位置。

private void btnAdd_Click(object sender, EventArgs e)
{
    for (int count = 0;count < 4; count++)
    {
        Label label = new Label();
        label.Location = new Point(10, (25 * count) + 2);
        label.Size = new Size(40, 20);
        label.ForeColor = System.Drawing.Color.White;
        label.Name = "label_" + (count + 1);
        label.Text = "Field " + (count + 1);
        panel3.Controls.Add(label);

        TextBox textbox = new TextBox();
        textbox.Location = new Point(60, 25 * count);
        textbox.Size = new Size(301, 20);
        textbox.Name = "textbox_" + (count + 1);
        textbox.TextChanged += new System.EventHandler(this.TextBox_Changed);
        panel3.Controls.Add(textbox);
    }        
}

如果您想为每次点击添加一个文本框和标签,您可以声明一个字段int count,用于计算创建的控件对的数量:

int count = 0;
private void button1_Click(object sender, EventArgs e)
{
        Label label = new Label();
        label.Location = new Point(10, (25 * count) + 2);
        label.Size = new Size(40, 20);
        label.ForeColor = System.Drawing.Color.White;
        label.Name = "label_" + (count + 1);
        label.Text = "Field " + (count + 1);
        panel3.Controls.Add(label);

        TextBox textbox = new TextBox();
        textbox.Location = new Point(60, 25 * count);
        textbox.Size = new Size(301, 20);
        textbox.Name = "textbox_" + (count + 1);
        textbox.TextChanged += new System.EventHandler(this.TextBox_Changed);
        panel3.Controls.Add(textbox);
        count++;
}