Reputation: 17
Generating only 1 textbox field and label. my plan is to generate only 4 fields in 1 panel
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);
}
Upvotes: 0
Views: 54
Reputation: 3014
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;
because your overwriting 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 = 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++;
}
Upvotes: 2