Friday, December 4, 2009

Code to Add Controls dynamically to Form

for (int k = 0; k < 5; k++)

{

TextBox t = new TextBox();

this.form1.Controls.Add(t);

LiteralControl l = new LiteralControl("<br/>");

this.form1.Controls.Add(l);

}



Note:We have taken the help of literal controls to place a TextBox in NextLine.
Here we are generating 5 TextBoxes.

PlaceHolder PlaceHolder1 = new PlaceHolder();

for (int i=1; i<=10; i++)
{
Label lbl = new Label();
lbl.Text = "Label" + i.ToString();
lbl.ID = "Label" + i.ToString();
PlaceHolder1.Controls.Add(lbl);
PlaceHolder1.Controls.Add(new LiteralControl("<br/>"));
} 

Here we are adding 10 Labels.