‘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.
|
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).
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.
The oCtrlDemo variable is the control that is added to the Placeholder control. The second line loads the user control into the oCtrlDemo variable.
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.
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.
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.
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.
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.
|