Posts Tagged dynamic
Dynamically Adding Controls in C# ASP.NET
Posted by nobodytalking in Web Development on June 20th, 2009
Adding C# controls dynamically is actually pretty simple:
public void showTextBoxes(){
//
TextBox txtBox = new TextBox();
txtBox.ID = “txtBox1″;
txtBox.TabIndex = 1;
txtBox.CssClass = “textBoxClass”;
//
form1.Controls.Add(txtBox);
}
Now this all works fine, but is somewhat limiting. Many times when your going to want to add controls you won’t know exactly how many at runtime. The number of controls needed may hinge on a users input. Possibly the value entered into a TextBox. This would then be handled with a loop:
public void showTextBoxes(){
form1.Controls.Add(new LiteralControl(“<table>”));
//
int i = 0;
//
int numberOfDays = Convert.ToInt16(txtDays.Text.ToString());
//
while (i <= numberOfDays){
//
TextBox txtBox = new TextBox();
//
txtBox.ID = “txtBox” + i;
txtBox.TabIndex = i;
txtBox.CssClass = “textBoxClass”;
//
form1.Controls.Add(new LiteralControl(“<tr><td>”));
//
form1.Controls.Add(txtBox);
//
form1.Controls.Add(new LiteralControl(“</td></tr>”));
//
i++;
}
form1.Controls.Add(new LiteralControl(“</table>”));
}
This function will create TextBoxes for however many days that the user has entered into the txtDays TextBox. The loop will also give each new TextBox a unique ID and TabIndex. This method though has some drawbacks, such as any information entered into the TextBoxes will be lost on a refresh of the page. So if your using C# and not Javascript for form validation you would lose all dynamically created Controls on validation.
In future posts I will look into ways to handle this issue and other similar situations.
