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

FREE 12 month online training for ASP.NET & MS Expression Studio and a Free copy of MS Expression Web with Windows Server Purchase
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


    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

     
  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 Asp.net 2008

Disclaimer - Privacy
© 2002-2014 DevASP.net