Dynamically Adding Controls

Dynamically Adding Controls

‘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.

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.

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 all 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+"

") For Each oControl In oPassed.Controls Response.Write(oControl.ID + "

") 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
")) Next End Sub

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

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).

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 2. The PlaceholderDemo Page: This page contains the phDemo Placeholder control and a button that, when clicked, adds a user control to phDemo.
Figure 3. The PlaceholderDemoUserControl: This user control 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.


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.

Adding Body User Controls
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.

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

   Body #1   Body #2   Body #2

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 11: The FormTemplate Page. This page displays when a Body query string variable is not passed in.
Figure 12: The FormTemplate Page. This page 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.

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.


About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist