This article will demonstrate how you can design and build flexibility into your ASP.NET pages by adding controls dynamically at runtime.

You'll learn to add simple controls to a page, progress to adding a user control into a Placeholder control, and then advance to using multiple Placeholder controls to build a template page that is flexible and easy to use.

Real World Applications

I'm a baseball fan. While I'd rather watch a game in person, more often than not, I'm watching it on the television. Something that you may not consciously notice while watching a game on television is the backstop. You see it every time the camera angle from the pitcher's point of view is displayed. Next time you're watching a baseball game on television, keep your eye on the advertising billboard on the backstop. You will notice that the advertising changes on a regular basis. Physically at the ballpark there is a blue screen located on the backstop and the advertising is inserted real time during the game for the television viewing audience. The players, coaches, and fans at the ballpark never see the advertising.

Even experienced developers may not have found the need to add a control at runtime.

You've got to admire the marketing genius who came up with this idea. I can imagine someone thinking, “If only there was a way I could sell the same billboard space to more than one advertiser. There's got to be a way!”

So why am I mentioning this in an article about dynamically adding controls at runtime to an ASP.NET page? Because inserting different advertising messages throughout the game demonstrates exactly the type of thing you can do by adding controls at runtime.

Why Add Controls at Runtime?

This seems like the logical place to start. For anyone who has already found the need to add controls at runtime in a VB, C++, or other Win32 applications, the question may seem fairly fundamental. If you haven't experienced the need it's a very valid question. Even experienced developers may not have found the need to add a control at runtime.

So, why add controls at runtime? The primary reasons are flexibility and power. Adding controls at runtime provides the flexibility to design user interfaces that can appear and behave differently to different users. Imagine a situation where, depending on the security level of the currently logged on user, certain controls are displayed and others are not. Yes, you could accomplish the same functionality by setting the visible property of the controls but with that solution you're potentially left with unattractive spaces in the UI where the invisible controls are located. An alternative solution would be to dynamically add the controls at runtime that the user is allowed to work with.

This is just one of a million different scenarios that lend themselves very well to take advantage of the flexibility and power of adding controls are runtime.

Basic ASP.NET Page Architecture

Before you can start adding controls you need to make sure you understand a few architectural issues. ASP.NET pages are built from controls. Everything on the page is a control. Labels, textboxes, command buttons, datagrids, static text, and even the HTMLForm, are represented by a control.

The Page.Controls collection contains a reference to every control contained on a page.

Private Sub cmdSave_Click( _
    ByVal sender As System.Object, _
    ByVal e As System.EventArgs) _
    Handles cmdSave.Click
        Dim oControl As Control
        For Each oControl In Page.Controls
            Me.ControlsList(oControl)
        Next
End Sub

Private Sub ControlsList(ByVal oPassed As Object)
     Dim oControl As Control
     Response.Write("Container:"+oPassed.ID+"<P>")
     For Each oControl In oPassed.Controls
         Response.Write(oControl.ID + "<P>")
     Next
End Sub

The above two procedures contain code that loops through the controls on a form and displays the ID property. The cmdSave_Click loops through the Controls collection on the page and passes each control to the ControlsList procedure, which loops through a container control and lists all the controls.

Adding Controls Programmatically

You add controls to a page (or other container controls as you'll see shortly) by adding controls to the Controls collection. That seems pretty straightforward to me. You call the Add() method to add a control to the Controls collection. The Add() method causes the control to be appended to the end of the Controls collection. You can add a control to a specific location in the Controls collection by using the AddAt() method.

Private Sub Page_Load(_
   ByVal sender As System.Object, _
   ByVal e As System.EventArgs) _
   Handles MyBase.Load

   Dim i As Integer
   For i = 1 To 5
     Controls.Add(New LiteralControl("Cool<br>"))
   Next
End Sub

The above code adds 5 Literal controls that each display the word Cool on the page. The resulting Web page appears in Figure 1.

Figure 1: Web page created by adding five Literal controls at runtime.
Figure 1: Web page created by adding five Literal controls at runtime.

Removing Controls Programmatically

It seems logical to me that if you can add controls at runtime you should be able to remove them as well. And you can. Use the Remove method to remove the control you pass to it.

Private Sub Page_Load(_
   ByVal sender As System.Object, _
   ByVal e As System.EventArgs) _
   Handles MyBase.Load

   Dim i As Integer
   For i = 1 To 5
     Controls.Add(New LiteralControl("Cool<br>"))
   Next
 
   Controls.Remove(Controls(1))
   Controls.Remove(Controls(2))
End Sub

Two of the Literal controls just added are removed in the code above.

ASP.NET pages are built from controls. Everything on the page is a control. Labels, textboxes, command buttons, datagrids, static text, and even the HTMLForm, are represented by a control.

Calling a collection's Clear method will remove all of the controls in the collection.

Introducing the Placeholder Control

While the Add method is great for adding a control at runtime, it doesn't offer you a lot of help in designating where the control will appear on the page.

The Placeholder control is an invisible container used to store dynamically added controls for a page. You use the Placeholder.Controls collection to add, insert, or remove a control from the PlaceHolder control.

Dim MyButton1 As HtmlButton = New HtmlButton()
MyButton1.InnerText = "My button"
MyPlaceholder.Controls.Add(MyButton)

The code above declares an HTMLButton object, assigns a value to a property, and adds it to a Placeholder control named MyPlaceholder. Of course this code assumes you've added a Placeholder named MyPlaceholder on your Web Form.

As you can see, adding controls to a placeholder at runtime is a pretty simple and powerful concept. Let's take it a step further to where the real power of this control becomes apparent. Instead of adding a single control or two, let's add a user control.

Dynamically Adding User Controls

To start, you'll create a new Web Form and you'll add three controls: a descriptive label, a button that will contain the code to add the user control, and a Placeholder control (see Figure 2).

Figure 2: The PlaceholderDemo page contains the phDemo Placeholder control and the button that adds a user control to phDemo.
Figure 2: The PlaceholderDemo page contains the phDemo Placeholder control and the button that adds a user control to phDemo.

Next, you'll create a user control named PlaceHolderDemoUserControl that you'll dynamically add to the page you just created. The user control consists of an HTML table and Web controls to create a typical data entry form (see Figure 3).

Figure 3: The PlaceholderDemoUserControl that will be loaded into the phDemo placeholder control at runtime.
Figure 3: The PlaceholderDemoUserControl that will be loaded into the phDemo placeholder control at runtime.

With your user control created it's time to write the code that will add it to your form at runtime (see Listing 1).

There are three key lines in Listing 1. The first creates the oCtrlDemo variable.

Public oCtrlDemo As Control

The oCtrlDemo variable is the control that is added to the Placeholder control. The second line loads the user control into the oCtrlDemo variable.

Me.oCtrlDemo = _
   LoadControl("PlaceholderDemoUserControl.ascx")

And the third key line adds the oCtrlDemo control into the phDemo placeholder.

Me.phDemo.Controls.Add(Me.oCtrlDemo)

That's it. When the user clicks on the button the PlaceholderDemoUserControl is loaded into the oCtrlDemo control and then it is added to the phDemo placeholder by calling the Add method on the phDemo Controls collection.

While the Add method is great for adding a control at runtime, it doesn't offer you a lot of help in designating where the control will appear on the page.

Sooner or later you are going to want to reference properties on the user control. Working with properties native to the Control class that the oCrtlDemo control is based on is very straightforward. You just assign or retrieve the property value like you would with any other object.

Private Sub Button1_Click(_
  ByVal sender As System.Object, _
  ByVal e As System.EventArgs) _
  Handles Button1.Click
   Me.oCtrlDemo = _
    LoadControl("PlaceholderDemoUserControl.ascx")
   Me.oCtrlDemo.Visible = False
   Me.phDemo.Controls.Add(Me.oCtrlDemo)
End Sub

You can see in the code above that the Visible property of the oCtrlDemo object has been set to False. Since Visible is a native property of the Control class this will work fine. The end result of this code is that the oCtrlDemo control will be added to the placeholder but it will not be visible.

Working with the properties native to the Control class is all well and good, but let's add a custom property named DemoProp to the PlaceholderDemoUserControl (see Listing 2). It just takes a simple step in order to access the DemoProp property. You'll covert the oCtrlDemo class to the type of class you added to it, namely the PlaceholderDemoUserControl. The following code demonstrates how to do this.

Private Sub Button1_Click(_
  ByVal sender As System.Object, _
  ByVal e As System.EventArgs) _
  Handles Button1.Click
   Me.oCtrlDemo = _
    LoadControl("PlaceholderDemoUserControl.ascx")
   CType(Me.oCtrlDemo, _
    PlaceholderDemoUserControl).DemoProp = 10
   Me.phDemo.Controls.Add(Me.oCtrlDemo)
End Sub

In this code, the key is to make sure that you convert the oCtrlDemo object from a plain Control object into an object of type PlaceholderDemoUserControl, so you'll use the CTYPE() function. Once you're done you can access the custom property, DemoProp.

I'll suggest one more change here just to drive home the point of working with properties on user controls. In this next code snippet, I'll add a line to the Page_Load method of the PlaceholderDemoControl user control that will set the Age textbox to the value in the DemoProp property.

Private Sub Page_Load(_
    ByVal sender As System.Object, _
    ByVal e As System.EventArgs) _
    Handles MyBase.Load
        Me.txtAge.Text = Me.DemoProp
End Sub

As you've seen so far, working with the Placeholder control and dynamically adding controls at runtime is not that difficult. Next, you can take what you've learned and extend it into a page template.

Dynamically Populating a Template Page

You're probably beginning to see the potential flexibility in this technique. You can take this idea even further and instead of a single placeholder control on a Web Form, let's create an HTML table with a header placeholder control across the top (plhHeader), a footer placeholder control across the bottom (plhFooter), a navigation placeholder down the left hand side of the form (plhNavigation), and finally a body placeholder in the center (plhBody). You'll name this Web Form FormTemplate.aspx (see Figure 4).

Figure 4: The FormTemplate.aspx page contains four different placeholder controls laid out in an HTML table.
Figure 4: The FormTemplate.aspx page contains four different placeholder controls laid out in an HTML table.

You'll also need to build the user controls that you'll add to the template. You'll add the Header.ascx user control (see Figure 5) to the plhHeader placeholder control. You'll add the Footer.ascx user control (see Figure 6) to the plhFooter placeholder. And (you guessed it) you'll add the Navigation.ascx user control (Figure 7) to the plhNavigation placeholder control. You'll use a few different user controls to display the content for the body section (plhBody) of the template (see Figures 8, 9, & 10).

Figure 5: The Header.ascx user control will be used to populate the plhHeader placeholder on the FormTemplate Web Form.
Figure 5: The Header.ascx user control will be used to populate the plhHeader placeholder on the FormTemplate Web Form.
Figure 6: The Footer.ascx user control will be used to populate the plhFooter placeholder on the FormTemplate Web Form.
Figure 6: The Footer.ascx user control will be used to populate the plhFooter placeholder on the FormTemplate Web Form.
Figure 7: The Navigation.ascx user control will be used to populate the plhNavigation placeholder on the FormTemplate Web Form.
Figure 7: The Navigation.ascx user control will be used to populate the plhNavigation placeholder on the FormTemplate Web Form.
Figure 8: The Body.ascx user control is one of three user controls used to populate the plhBody placeholder on the FormTemplate Web Form.
Figure 8: The Body.ascx user control is one of three user controls used to populate the plhBody placeholder on the FormTemplate Web Form.
Figure 9: The Body2.ascx user control is one of three user controls used to populate the plhBody placeholder on the FormTemplate Web Form.
Figure 9: The Body2.ascx user control is one of three user controls used to populate the plhBody placeholder on the FormTemplate Web Form.
Figure 10: The Body3.ascx user control is one of three user controls used to populate the plhBody placeholder on the FormTemplate Web Form.
Figure 10: The Body3.ascx user control is one of three user controls used to populate the plhBody placeholder on the FormTemplate Web Form.

Listing 3 contains the complete class definition for the FormTemplate Web Form class. In addition to the Page_Load method you will find four additional methods that are each responsible for loading a specific placeholder control.

The HeaderSetup method accepts no arguments and adds the Header.ascx user control to the plhHeader placeholder. The FooterSetup method accepts no arguments and adds the Footer.ascx user control to the plhFooter placeholder. The NavigationSetup accepts no arguments and adds the Navigation.ascx user control to the plhNavigation placeholder. You could easily extend these methods to accept an argument that specifies exactly which user control to add. That is exactly how the body content of the page is controlled. The BodySetup method accepts one string argument (strCode) and adds one of the Body user controls (Body.ascx, Body2.ascx, or Body3.ascx) to the plhBody placeholder depending on the value contained in strCode.

When the page loads for the first time, the Body query string variable will be blank and will result in neither of the body user controls being added (see Figure 11). In this situation you could load a “home” user control to display the initial content. I'll leave that as an exercise for you.

Figure 11: The FormTemplate page that displays when a Body query string variable is not passed in.
Figure 11: The FormTemplate page that displays when a Body query string variable is not passed in.

So, how does the Body query string variable get set? The links in the Navigation user control hold the answer to this question.

<asp:LinkButton id="LinkButton1" runat="server" 
CommandArgument="1">Body #1</asp:LinkButton>

<asp:LinkButton id="Linkbutton2" runat="server"
CommandArgument="2">Body #2</asp:LinkButton>

<asp:LinkButton id="Linkbutton2" runat="server" CommandArgument="2">Body #2</asp:LinkButton>

Setting the CommandArgument for each LinkButton to 1, 2, or 3 determines which Body user control to display. In addition, each LinkButton has its Click event handled by the FilterLetter_Click method.

Private Sub FilterLetter_Click(_
   ByVal sender As System.Object, _
   ByVal e As System.EventArgs) _
   Handles LinkButton1.Click, _
           Linkbutton2.Click, _
           Linkbutton3.Click

   If sender.CommandArgument = 1 Then
     Response.Redirect("Formtemplate.aspx?Body=1")
   ElseIf sender.CommandArgument = 2 Then
     Response.Redirect("Formtemplate.aspx?Body=2")
   ElseIf sender.CommandArgument = 3 Then
     Response.Redirect("Formtemplate.aspx?Body=3")
   End If
End Sub

In this code the FormTemplate page is posted to and the Body query string gets passed into it.

Contained in the Page_Load is where the Body query string is captured and subsequently passed into the BodySetup method.

Dim strBodyCode As String = _
    Request.QueryString("Body")

Me.HeaderSetup()
Me.FooterSetup()
Me.NavigationSetup()
Me.BodySetup(strBodyCode)

Let's walk through a typical user action. Clicking on the Body #3 LinkButton on the Navigation bar causes a “3” to be posted back to the FormTemplate page. This in turn causes a “3” to be passed into the BodySetup method causing the Body3.ascx user control to be loaded into the plhBody placeholder. The resulting page is in Figure 12.

Figure 12: The FormTemplate page that displays when the Body query string variable is set to 3.
Figure 12: The FormTemplate page that displays when the Body query string variable is set to 3.

Obviously the template you created here is just one of an infinite number of templates you can design and build yourself for your ASP.NET Web sites.

Conclusion

Well that wraps up this article. I'm always interested to hear your feedback about the material covered here. As you can see, working with the Placeholder control and adding controls at runtime provides you with the flexibility to design generic templates and the power to leverage them over and over again.

Listing 1: Class code for the PlaceholderDemo.aspx Web Form

Public Class PlaceholderDemo
    Inherits <a href="http://System.Web.UI">System.Web.UI</a>.Page


    Public oCtrlDemo As Control

    Protected WithEvents Label1 As _
        <a href="http://System.Web.UI">System.Web.UI</a>.WebControls.Label
    Protected WithEvents phDemo As _
        <a href="http://System.Web.UI">System.Web.UI</a>.WebControls.PlaceHolder
    Protected WithEvents Button1 As _
        <a href="http://System.Web.UI">System.Web.UI</a>.WebControls.Button

    Private Sub Page_Load(_
       ByVal sender As System.Object, _
       ByVal e As System.EventArgs) _
       Handles MyBase.Load
        'Put user code to initialize the page here
    End Sub

    Private Sub Button1_Click(_
       ByVal sender As System.Object, _
       ByVal e As System.EventArgs) Handles Button1.Click
        Me.oCtrlDemo = _
           LoadControl("PlaceholderDemoUserControl.ascx")
        Me.phDemo.Controls.Add(Me.oCtrlDemo)
    End Sub
End Class

Listing 2: Class code for the PlaceholderDemoUserControl.ascx user control

Public Class PlaceholderDemoUserControl
    Inherits <a href="http://System.Web.UI">System.Web.UI</a>.UserControl
    Protected WithEvents Label1 As _
        <a href="http://System.Web.UI">System.Web.UI</a>.WebControls.Label
    Protected WithEvents txtFirstName As _
        <a href="http://System.Web.UI">System.Web.UI</a>.WebControls.TextBox
    Protected WithEvents Label2 As _
        <a href="http://System.Web.UI">System.Web.UI</a>.WebControls.Label
    Protected WithEvents txtLastName As _
        <a href="http://System.Web.UI">System.Web.UI</a>.WebControls.TextBox
    Protected WithEvents Label3 As _
        <a href="http://System.Web.UI">System.Web.UI</a>.WebControls.Label
    Protected WithEvents txtAge As _
        <a href="http://System.Web.UI">System.Web.UI</a>.WebControls.TextBox

    Private m_MyProperty As Integer

    Public Property DemoProp() As Integer
        Get
            Return m_MyProperty
        End Get

        Set(ByVal MyValue As Integer)
            m_MyProperty = MyValue
        End Set
    End Property

    Private Sub Page_Load(_
       ByVal sender As System.Object, _
       ByVal e As System.EventArgs) Handles MyBase.Load
        'Put user code to initialize the page here
    End Sub
End Class

Listing 3: Class code for the FormTemplate.aspx Web Form

Public Class FormTemplate
    Inherits <a href="http://System.Web.UI">System.Web.UI</a>.Page

    Protected WithEvents plhHeader As _
        <a href="http://System.Web.UI">System.Web.UI</a>.WebControls.PlaceHolder
    Protected WithEvents plhNavigation As _
        <a href="http://System.Web.UI">System.Web.UI</a>.WebControls.PlaceHolder
    Protected WithEvents plhBody As _
        <a href="http://System.Web.UI">System.Web.UI</a>.WebControls.PlaceHolder
    Protected WithEvents plhFooter As _
        <a href="http://System.Web.UI">System.Web.UI</a>.WebControls.PlaceHolder

    Private Sub Page_Load(_
       ByVal sender As System.Object, _
       ByVal e As System.EventArgs) Handles MyBase.Load

        Dim strBodyCode As String = _
            Request.QueryString("Body")

        Me.HeaderSetup()
        Me.FooterSetup()
        Me.NavigationSetup()
        Me.BodySetup(strBodyCode)

    End Sub

    Private Sub HeaderSetup()
        Dim oMyControl As Control
        oMyControl = LoadControl("Header.ascx")

        Me.plhHeader.Controls.Clear()
        Me.plhHeader.Controls.Add(oMyControl)
    End Sub

    Private Sub BodySetup(ByVal strCode As String)
        Dim oMyControl As Control

        If strCode = "1" Then
            oMyControl = LoadControl("Body.ascx")
        ElseIf strCode = "2" Then
            oMyControl = LoadControl("Body2.ascx")
        ElseIf strCode = "3" Then
            oMyControl = LoadControl("Body3.ascx")
        End If

        If Not strCode Is Nothing Then
            Me.plhBody.Controls.Clear()
            Me.plhBody.Controls.Add(oMyControl)
        End If
    End Sub

    Private Sub FooterSetup()
        Dim oMyControl As Control
        oMyControl = LoadControl("Footer.ascx")

        Me.plhFooter.Controls.Clear()
        Me.plhFooter.Controls.Add(oMyControl)
    End Sub

    Private Sub NavigationSetup()
        Dim oMyControl As Control
        oMyControl = LoadControl("Navigation.ascx")

        Me.plhNavigation.Controls.Clear()
        Me.plhNavigation.Controls.Add(oMyControl)
    End Sub
End Class