Search - Articles
DevASP.NET for ASP.NET, VB.NET, XML and C# (C-Sharp) Developers Tuesday, March 03, 2009
Dev Articles
Search Directory
SQL Server

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. 

  1. Create a new empty website in visual studio 2010 either in C# or in VB.NET
  2. Add a new item (web form) in the website
  3. Open code behind file and write the following code in the Page_Load method or OnInit method
  4. First create an instance of the control and set its properties then add this control to the form


    if (!IsPostBack) {

      TextBox myTextBox = new TextBox();
      myTextBox.ID = "txtBoxSample";

      Button myButton = new Button();
      myButton.ID = "btnSample";
      myButton.Text = "Sample Button";

      Label myLabel = new Label();
      myLabel.ID = "lblSample";
      myLabel.Text = "Sample Label";



    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"

        Dim myButton As New Button()
        myButton.ID = "btnSample"
        myButton.Text = "Sample Button"

        Dim myLabel As New Label()
        myLabel.ID = "lblSample"
        myLabel.Text = "Sample Label"

      End If

    End Sub

  5. Hit "F5" to run the project and that web page contains one TextBox, one Button and one Label control on it.



Add Article Comment:
Name :
Email Address :
Comments :
<< Master pages in 2008

Disclaimer - Privacy
© 2002-2017