Dynamically create TextBoxes with C# on Windows Form

May 5, 2011 | Posted by: admin | C#, Programming language | 6 Comments

This article demonstrates how to dynamically create TextBoxes, CheckBox control with C# on Windows Form.

the below codes dynamically creates TextBox and CheckBox controls, sets their IDs and positions, and then binds them to the Form panel.

Method 1

private void Method1()
{
for(int i = 0; i<boxes; i++)
{
TextBox tb = new TextBox();
tb.Location = new System.Drawing.Point(40, 120 + i * 20);
tb.Name = "TextBoxName" + i.ToString();
tb.Size = new System.Drawing.Size(184,20);
tb.TabIndex = i + 2;
tb.Text = String.Empty;
panel1.Controls.Add(tb);
}
}

Method 2

private ArrayList textboxes;
private int Tboxes = 3;
private void Method2()
{
int i = 0;
this.textboxes = new ArrayList();
for(i = 0; i<Tboxes; i++)
{
this.textboxes.Add( new TextBox() );
((TextBox)this.textboxes[i]).Location = new System.Drawing.Point(40, 36 + i * 20);
((TextBox)this.textboxes[i]).Name = "TextBoxName" + i.ToString();
((TextBox)this.textboxes[i]).Size = new System.Drawing.Size(184,20);
((TextBox)this.textboxes[i]).TabIndex = i + 2;
((TextBox)this.textboxes[i]).Text = String.Empty;
panel1.Controls.Add(((TextBox)this.textboxes[i]));
}
}

Dynamically create CheckBox with C# on Windows Form

CheckBox[] chk = new CheckBox[10];
int height = 1;
int padding = 10;
for (int i = 0; i <= 9; i++)
{
chk[i] = new CheckBox();
chk[i].Name = i.ToString();
chk[i].Text = i.ToString();
chk[i].TabIndex = i;
chk[i].AutoCheck = true;
chk[i].Bounds = new Rectangle(10, 20 + padding + height, 40, 22);
panel1.Controls.Add(chk[i]);
height += 22;
}

Comments (6)

 

  1. prosenjit says:

    very ince example. i will hope lot of help of future

  2. chari says:

    excellent . A lot of help for me

  3. Shashidhar says:

    Very Helpful

  4. asdwsa says:

    adsfsad

  5. Saran says:

    Thank you for this writeup. It was very informative. Please continue to creat more like this in the future!

  6. BUdi says:

    how i can get the value with this Dynamically checkbox??

Leave a Reply