[英]Dynamically Created Label and Textbox
Generating only 1 textbox field and label. 仅生成1个文本框字段和标签。 my plan is to generate only 4 fields in 1 panel
我的计划是在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);
}
You can use a for loop to add more than one textbox and label at the same time and you have to remove textbox.Top = 4;
您可以使用for循环同时添加多个文本框和标签,并且必须删除文本框
textbox.Top = 4;
because your overwriting label.Location = new Point(10, (25 * count) + 2);
因为您的覆盖
label.Location = new Point(10, (25 * count) + 2);
and all of your controls will have the same position. 并且所有控件的位置相同。
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);
}
}
If you want to add one textbox and label per click you can declare a field int count
that counts the number of created control pairs: 如果要在每次单击中添加一个文本框和标签,则可以声明一个字段
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++;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.