Loading User Controls Programmatically


Loading User Controls Programmatically

Instead of declaring a user control in a page, you can add the user control programmatically in your code. For example, imagine that you want to add a featured product section to the home page of your Web site. Imagine, furthermore, that each featured product has different layout requirements. You can create user controls that correspond to each featured product and randomly load one of the controls each time the home page is displayed.

Listing 5.18 and 5.19 contain two featured products.

Listing 5.18 FeaturedProduct1.ascx
 <%@ ClassName="FeaturedProduct1" %> <Script runat="Server"> Public BackColor As String = "lightgreen" </Script> <table width="200" cellpadding="10"   cellspacing="0" bgcolor="<%=BackColor%>"> <tr>   <td>   <h3>Hammers on Sale!</h2>   Quality hammers are now on sale in the   hardware department.   </td> </tr> </table> 

The C# version of this code can be found on the CD-ROM.

Listing 5.19 FeaturedProduct2.ascx
 <%@ ClassName="FeaturedProduct2" %> <Script runat="Server"> Public BackColor As String = "lightgreen" </Script> <table width="200" cellpadding="10"   cellspacing="0" bgcolor="<%=BackColor%>"> <tr>   <td>   <h3>Blenders on Sale!</h3>   See our selection of blenders in the   home appliance deparment.   </td> </tr> </table> 

The C# version of this code can be found on the CD-ROM.

The page in Listing 5.20 demonstrates how you can randomly display one of the featured products.

Listing 5.20 DisplayFeaturedProduct.aspx
 <Script runat="Server"> Sub Page_Load   Dim strFeatured As String   Dim RanNum As New Random   Dim ctlControl As Control   strFeatured = "FeaturedProduct" & RanNum.Next( 1, 3 ) & ".ascx"   ctlControl = LoadControl( strFeatured )   plhFeatured.Controls.Add( ctlControl ) End Sub </Script> <html> <head><title>DisplayFeaturedProduct.aspx</title></head> <body> <asp:PlaceHolder   id="plhFeatured"   Runat="Server" /> </body> </html> 

The C# version of this code can be found on the CD-ROM.

The page in Listing 5.20 uses the LoadControl() method to dynamically load a user control. This method takes the path to a user control as its only parameter.

NOTE

An example of an application that makes extensive use of dynamically loaded user controls is the ASP.NET Community Starter Kit. The Community Starter Kit takes advantage of user controls to skin the pages in the application. If you want to dramatically modify the appearance of a Web site created with the Community Starter Kit, then you can select a new set of skins (user controls) that are loaded for all the pages in the application. You can download the ASP.NET Community Starter Kit from www.ASP.net.


Specifying the Type of a User Control

One problem with the LoadControl method used in the previous section is that it returns an object of type Control . It does not return the actual type of the user control. This means that you cannot set any of the properties or call any of the methods of a user control loaded with the LoadControl method without doing a little extra work.

For example, the featured product user controls in Listings 5.18 and 5.19 both have a BackColor property. Since the LoadControl method returns these user controls as generic Control objects, you cannot assign a value to BackColor .

Before you set a property of a dynamically loaded user control, you must cast the user control to the proper type. If you reexamine Listings 5.18 and 5.19, you'll notice that both listings begin with a directive that specifies the user control's ClassName . The ClassName attribute declares the user control's type.

The page in Listing 5.21 illustrates how you can convert a dynamically loaded user control to the proper type and set its properties.

Listing 5.21 DisplayFeaturedProductType.aspx
 <%@ Register TagPrefix="SuperCompany" TagName="FeaturedProduct1"   Src="FeaturedProduct1.ascx" %> <%@ Register TagPrefix="SuperCompany" TagName="FeaturedProduct2"   Src="FeaturedProduct2.ascx" %> <Script runat="Server"> Sub Page_Load   Dim strFeatured As String   Dim RanNum As New Random   Dim ctlControl As Control   Select RanNum.Next( 1, 3 )   Case 1     ctlControl = LoadControl( "FeaturedProduct1.ascx" )     CType( ctlControl, FeaturedProduct1 ).BackColor = "Yellow"   Case 2     ctlControl = LoadControl( "FeaturedProduct2.ascx" )     CType( ctlControl, FeaturedProduct2 ).BackColor = "Yellow"   End Select   plhFeatured.Controls.Add( ctlControl ) End Sub </Script> <html> <head><title>DisplayFeaturedProductType.aspx</title></head> <body> <asp:PlaceHolder   id="plhFeatured"   Runat="Server" /> </body> </html> 

The C# version of this code can be found on the CD-ROM.

The CType function is used in Listing 5.21 to convert the user control being displayed to the proper type. Notice that you must register any user control that you might use in the page with a Register directive. The top of Listing 5.21 contains the following two Register directives:

 
 <%@ Register TagPrefix="SuperCompany" TagName="FeaturedProduct1"   Src="FeaturedProduct1.ascx" %> <%@ Register TagPrefix="SuperCompany" TagName="FeaturedProduct2"   Src="FeaturedProduct2.ascx" %> 

If you neglect to register a user control, you'll receive a Type is not defined error message when you attempt to convert the user control to a particular type.

Code-Behind and User Controls

Instead of registering each and every user control that you might use on a page, you can derive multiple user controls from a single class. For example, you can create a single FeaturedProduct class that has a BackColor property. Next, you can derive all of the FeaturedProduct user controls from this class. After you do this, you can set the BackColor property for any featured product by converting the user control to an instance of the FeaturedProduct class.

NOTE

In the next chapter, "Separating Code From Presentation," the topic of building custom classes and code-behind files is discussed in detail.


The first step is to create the FeaturedProduct class. This class is contained in Listing 5.22.

Listing 5.22 FeaturedProduct.vb
 Imports System Imports System.Web.UI Imports System.Web.UI.WebControls Public Class FeaturedProduct Inherits UserControl Public BackColor As String = "lightgreen" End Class 

The C# version of this code can be found on the CD-ROM.

Notice that the FeaturedProduct class inherits from the UserControl class. The class contains a single BackColor property.

After you create the source file for the class, you'll need to compile it. You can compile the class in Listing 5.22 by executing the following statement from the command line:

 
 vbc /t:library /r:System.dll,System.Web.dll FeaturedProduct.vb 

Next, you'll need to copy the compiled FeaturedProduct class file, FeaturedProduct.dll , to the bin directory located under your application's root directory (If this bin directory does not exist, you can create it).

Now that you have a FeaturedProduct class, you can derive each of the featured product user controls from this class as illustrated in Listings 5.23 and 5.24.

Listing 5.23 Featured1.ascx
 <%@ Inherits="FeaturedProduct" %> <table width="200" cellpadding="10"   cellspacing="0" bgcolor="<%=BackColor%>"> <tr>   <td>   <h3>Hammers on Sale!</h2>   Quality hammers are now on sale in the   hardware department.   </td> </tr> </table> 

The C# version of this code can be found on the CD-ROM.

Listing 5.24 Featured2.ascx
 <%@ Inherits="FeaturedProduct" %> <table width="200" cellpadding="10"   cellspacing="0" bgcolor="<%=BackColor%>"> <tr>   <td>   <h3>Blenders on Sale!</h3>   See our selection of blenders in the   home appliance deparment.   </td> </tr> </table> 

The C# version of this code can be found on the CD-ROM.

Both of the user controls contained in Listings 5.23 and 5.24 contain an Inherits attribute that indicates that both classes are derived from the base FeaturedProduct class.

Finally, Listing 5.25 illustrates how you can use the featured product user controls in an ASP.NET page. Notice that you do not need to include Register directives before using the controls.

Listing 5.25 DisplayFeaturedProductCodeBehind.aspx
 <Script runat="Server"> Sub Page_Load   Dim strFeatured As String   Dim RanNum As New Random   Dim ctlControl As Control   strFeatured = "Featured" & RanNum.Next( 1, 3 ) & ".ascx"   ctlControl = LoadControl( strFeatured )   Ctype( ctlControl, FeaturedProduct ).BackColor="Orange"   plhFeatured.Controls.Add( ctlControl ) End Sub </Script> <html> <head><title>DisplayFeaturedProductCodeBehind.aspx</title></head> <body> <asp:PlaceHolder   id="plhFeatured"   Runat="Server" /> </body> </html> 

The C# version of this code can be found on the CD-ROM.



ASP.NET Unleashed
ASP.NET 4 Unleashed
ISBN: 0672331128
EAN: 2147483647
Year: 2003
Pages: 263

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net