Programmatically adding WebControls to Web Page in ASP.NET
Author: Usman Lateef
Adding web controls to a web page programmatically means to create controls at run time.
One solution to create controls in ASP.NET is to create them in .aspx page and make them visible at run time according to your needs. But in this article, you will learn how to add different web controls to a web page programmatically at run time. To add a control programmatically on a web page, there must be a container Control on Web Page. As we know in ASP.NET there always is a “form” control available so we will use it as our container control.
- Create a new empty website in visual studio 2010 either in C# or in VB.NET
- Add a new item (web form) in the website
- Open code behind file and write the following code in the Page_Load method or OnInit method
- First create an instance of the control and set its properties then add this control to the form
C#
if (!IsPostBack) {
TextBox myTextBox = new TextBox();
myTextBox.ID = "txtBoxSample";
this.form1.Controls.Add(myTextBox);
Button myButton = new Button();
myButton.ID = "btnSample";
myButton.Text = "Sample Button";
this.form1.Controls.Add(myButton);
Label myLabel = new Label();
myLabel.ID = "lblSample";
myLabel.Text = "Sample Label";
this.form1.Controls.Add(myLabel);
}
VB.NET
Protected Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Me.Load
If Not IsPostBack Then
Dim myTextBox As New TextBox()
myTextBox.ID = "txtBoxSample"
Me.form1.Controls.Add(myTextBox)
Dim myButton As New Button()
myButton.ID = "btnSample"
myButton.Text = "Sample Button"
Me.form1.Controls.Add(myButton)
Dim myLabel As New Label()
myLabel.ID = "lblSample"
myLabel.Text = "Sample Label"
Me.form1.Controls.Add(myLabel)
End If
End Sub
- Hit "F5" to run the project and that web page contains one TextBox, one Button and one Label control on it.