How do I dynamically add controls to a Web Form?
Adding Controls at the Bottom of a Form
To dynamically add a control to the bottom of a Web Form, first instantiate an instance of the control, then add it to the form's Controls collection.
For example, the following code adds a Label to a Web Form. Notice the last line of code adds a LiteralControl line break after the label, causing subsequent controls to be added to the next line.
In C:
Label lblTest = new Label();
lblTest.Text = "My Label Text: ";
Controls.Add(lblTest);
Controls.Add(new LiteralControl("<br>"));In VB .NET:
Dim lblTest As New Label()
lblTest.Text = "My Label Text: "
Controls.Add(lblTest)Controls.Add(New LiteralControl("<br>"))Adding Controls at a Specific Location in a Form
When you add controls to a form using Controls.Add(), controls are placed at the bottom of a form. If you want to place controls at a specific location in a form, you can accomplish this by using a PlaceHolder.
Select the Web Forms tab in the Visual Studio Toolbox. Drag and drop a PlaceHolder onto the form. Position the PlaceHolder control whereever you want the real control to appear. For example, the following image shows an PlaceHolder located above a DataGrid:
In the Web Form's Load, you can add code to instantiate a control and add it to the PlaceHolder's Controls collection. For example, the following code instantiates a Label, sets its Text property and adds it to the PlaceHolder.
In C#:
private void Page_Load(object sender, System.EventArgs e)
{
Button btnMyButton = new Button();
btnMyButton.Text = "Added dynamically!";
this.PlaceHolder1.Controls.Add(btnMyButton);
}In VB .NET:
Private Sub Page_Load(sender As Object, e As System.EventArgs)
Dim btnMyButton As New Button()
btnMyButton.Text = "Added dynamically!"
Me.PlaceHolder1.Controls.Add(btnMyButton)
End SubWhen you run the form, it looks like this:
© (c) 2026 Oak Leaf Enterprises, Inc., 1996-2026 • Updated: 04/26/18
Comment or report problem with topic
