Build a Basic Template Control

Take charge of your Web pages’ layout.

Doug Seven

October 30, 2009

9 Min Read
ITPro Today logo in a gray background | ITPro Today

If you have been working withASP.NET even for a littlewhile, you've probably encountered a template control, though you might nothave realized it. Template controlsare server controls, inside which you can specify the HTML layout of one ormore templates. This gives you flexibility when using the control whilemaintaining the control's functionality. You can use template controls tocreate standard layouts for information on a Web site or to provide a controlthat enables variations on a single layout.

Server controls such as Repeater, DataList,and DataGrid fall into the template control category. More specifically,these are data-bound template controls. In this column I'll show you how tobuild a basic template control (the downloadable source code for this articleis available in both C# and Visual Basic .NET.)

A template control lets you control the layout of therendered HTML by defining the layout of a template within the control itself,as shown here:

      Title
    This is the ItemTemplate area  

This control would be rendered with any HTML defined inthe control itself as well as the HTML between the and tags within the control. You can use thiscapability when you have a prescribed format for rendering information,although the information itself might change. For example, you could use atemplate control if company policy dictates that all information related tocurrency conversion be shown in an HTML table, with a header row displaying thetext "Currency Information", a row displaying the information, and a rowdisplaying some copyright information. Creating and using a template control ina scenario like this ensures all information related to currency conversion isdisplayed in the approved format (see Figure 1).


Figure 1. The CurrencyInformation template control consists of apredefined header and footer row, with an ItemTemplate in the middle. In thisfigure, the ItemTemplate contains data about a currency conversion request.

 

Build the Control Structure

The CurrencyInformation control shown in Figure 1is a basic template control. In this case, the CurrencyInformationcontrol contains only one template - the ItemTemplate. The DataGridexposes a HeaderTemplate, FooterTemplate, ItemTemplate,and AlternatingItemTemplate, so you can construct any of thesetemplates. The header and footer rows of the CurrencyInformation controlare predefined within the control, providing a predefined table structure fordisplaying information. An instance of the CurrencyInformation controlwith nothing in the ItemTemplate is shown in Figure 2.

 


Figure 2. When the ItemTemplate is empty, the control is renderedshowing only the header and footer rows. This figure shows how the predefinedportions of the control are rendered regardless of what is in the ItemTemplate.

The CurrencyInformation control exposes only asingle property: ItemTemplate. The ITemplate interface is used asthe property's data type, which lets you specify the template HTML eitherprogrammatically or declaratively.

The basic structure for the CurrencyInformationcontrol is shown in Figure 3.

using System;using System.Web.UI;using System.Web.UI.HtmlControls;using System.Web.UI.WebControls;using System.ComponentModel; namespace MyTemplateControls{   [ToolboxData(    "<{0}:CurrencyInformation runat=server>" +    "")]  public class CurrencyInformation :    System.Web.UI.WebControls.WebControl,    INamingContainer  {    //Properties go here     //Methods go here  }}

Figure 3. The CurrencyInformation template controlderives from the System.Web.UI.WebControls.WebControl class and implements theINamingContainer interface. I've added comments indicating when the code in theupcoming listings will be added.

Now I'll tell you about each part of the control. Noticethat, like other custom controls, the CurrencyInformation controlderives from the System.Web.UI.WebControls.WebControl class. This classprovides all the basic functionality of a WebControl without having towrite it yourself. Also, the CurrencyInformation control implements the INamingContainerinterface, which ensures all child controls are uniquely named. The ID of thechild control is appended with the parent control ID and an underscore("CurrencyInformation1_Control1"). The ToolboxData attribute is appliedto the class. This attribute, which is not required, defines how the code willlook in a Web form when the control is dragged from the Toolbox to the Web formin Visual Studio .NET.

 

Expose Templates as Properties

The ITemplate interface serves as the data type forany property in the control that is a template. This lets you expose thetemplates as properties of the control so other developers can define thetemplate HTML either programmatically or declaratively. See Figure 4 for thedefinition of the ItemTemplate property.

//C# Syntaxprivate ITemplate _itemTemplate;[TemplateContainer(typeof(CurrencyInformation))]public ITemplate ItemTemplate{  get{return _itemTemplate;}  set{_itemTemplate = value;}} 'Visual Basic .NET syntaxPrivate _itemTemplate As ITemplate _Public Property ItemTemplate() As ITemplate  Get    Return _itemTemplate  End Get   Set(ByVal Value As ITemplate)    _itemTemplate = Value   End SetEnd Property

Figure 4. The ItemTemplate property uses the ITemplateinterface as its data type, which enables the control to use the code insidethe template tags, and at run time, render that content inside the controllayout.

The ITemplate interface defines how to add thetemplate HTML to the control. This interface defines a single method, InstantiateIn,which creates the template HTML that is passed in the control as an argument tothe method:

Panel itemContainer = new Panel();_itemTemplate.InstantiateIn(itemContainer);

This code creates a Panel control and instantiatesthe template HTML inside Panel. This is the sole purpose of the ITemplateinterface. The ASP.NET Framework implements the ITemplate interface,which is never implemented directly by a class.

 

Override the CreateChildControlsMethod

The heart of building a template control is in the CreateChildControlsmethod. You override this method and build the control structure, instantiatingthe template in the appropriate place. For the CurrencyInformationtemplate, you must first build the table structure and the header row. Next,you instantiate the template in a Panel control and add the Panelcontrol to the second row of the table. Finally, you create the footer row andadd the table to the parent control's Controls collection. The CreateChildControlsmethod is shown in Figure 5.

protected override void CreateChildControls(){  //Create the top-level Table object  HtmlTable t = new HtmlTable();  t.Width = this.Width.ToString();  t.CellPadding = 4;  t.CellSpacing = 0;  t.Border = 0;  t.Attributes["style"] = "border-width:1px;" +


Use a Template Control on a WebForm

You can use the CurrencyInformation control in aWeb application by making a reference to the MyTemplateControlsassembly. In Visual Studio .NET, you add a reference by selecting Add Reference under the Project menu. This actionmakes a copy of MyTemplateControls.dll in the Web application's bin directory.If you are not using Visual Studio .NET, you can copy theMyTemplateControls.dll to your Web application's bin directory.

In the Web form, you register the assembly on the pageusing the @ Register directive:

<%@ Register TagPrefix="cc1" Namespace="MyTemplateControls" Assembly="MyTemplateControls" %>

Once the control is registered, you can use it on the Webform like any other server control. Here is the code for using the CurrencyInformationcontrol and filling the ItemTemplate with declarative text:

      Disclaimer: Currency conversions are    provided as a sample and are not necessarily guaranteed    to be accurate. The MoneyUtilities Web service is    provided by DotNetJunkies.com with no guarantees or    warranties.  

You can place static text inside the ItemTemplate;this text is rendered inside the control. You define the CurrencyInformationcontrol as you do any other server control, by specifying the TagPrefixand TagName and adding the runat="server" attribute.Inside the control tags, you define the template by using the property name ().Inside the item template, you simply add some text.

You also can use other servercontrols inside the template (see Figure 6).

    From:        
    From Amount:        
    To:        
    To Amount:        
     Conversion Date:      

Figure 6. You can use ASP.NET server controls or othercustom server controls inside the ItemTemplate. These controls processnormally, but their output is rendered inside the template control.

In the Web form's codebehind, you can retrieve currencyconversion information dynamically and populate the server controls in the template.The key thing to remember is the server controls in the template are childcontrols of the CurrencyInformation control. Just as controls embeddedin a DataGrid can't be accessed directly in Web form codebehind, neithercan the server controls in the CurrencyInformation control. Instead, youneed to use the Control.FindControl method. This method is inheritedinto the CurrencyInformation control because it derives from WebControl,which in turn derives from Control.

The FindControl method takes an ID value as a Stringand returns a Control instance if it finds a matching control. Once thecontrol is found, it needs to be cast as its particular control type before youcan access its properties. For this example, you access the DotNetJunkies.comMoneyUtilities Web service and execute a currency conversion. Then you set theproperties of the server controls in the template (see Figure 7).

private void btnGo_Click(object sender, System.EventArgs e){  com.dotnetjunkies.www.MoneyUtilities mu =    new com.dotnetjunkies.www.MoneyUtilities();  com.dotnetjunkies.www.Conversion c;  c = mu.ConvertMoney(    Single.Parse(txtAmount.Text.Trim()),    ddlFrom.SelectedItem.Value,    ddlTo.SelectedItem.Value  );    ((Label)CI1.FindControl("lblFrom")).Text =     c.FromMoneyType;   ((Label)CI1.FindControl("lblTo")).Text =    c.ToMoneyType;   ((Label)CI1.FindControl("lblFromAmount")).Text =    c.FromAmount.ToString("n");   ((Label)CI1.FindControl("lblToAmount")).Text =    c.ToAmount.ToString("n");   ((Label)CI1.FindControl("lblDate")).Text =    c.ConversionDate;}

Figure 7. To access the controls in the ItemTemplatefrom a Web form code-behind class, you must use the FindControl method. Thismethod locates the control by its ID value and returns it as an instance of theControl class. Once the control is found, you must cast it back to its correctdata type before accessing its properties and methods.

In the preceding example, the Web form contains two DropDownLists,a TextBox, a LinkButton, and the CurrencyInformationcontrol. The user selects two countries from the DropDownLists andenters an amount into the TextBox. When the user clicks on the LinkButton,the DotNetJunkies.com MoneyUtilities proxy class is instantiated and the ConvertMoneymethod is executed. Once the Web method completes, you use the FindControlmethod to locate the appropriate Label controls and set their Textproperties with the appropriate values. The result is shown in Figure 8.

 


Figure 8. The CurrencyInformation control can be used in a variety ofways. In this figure, you can see the control used with some ASP.NET servercontrols in the ItemTemplate and the control with static text in theItemTemplate.

You can use these concepts to build countless templatecontrols with one, two, or any number of templates within them. This is simplyone example of control development in ASP.NET, which offers vast possibilitieswhen you use your imagination.

The code referenced in thisarticle is available for download.

 

Doug Seven is aco-founder of DotNetJunkies (http://www.dotnetjunkies.com),a .NET training company. He has had previous technical roles at Nordstrom,Microsoft, and GiftCertificates.com, and he has experience as a trainingspecialist at Seattle Coffee Company. Doug co-authored Programming Data-Driven Web Applicationswith ASP.NET and ASP.NET: Tips, Tutorials & Code (Sams), and Professional ADO.NET and Professional ASP.NET Security (Wrox).E-mail Doug at mailto:[email protected].

Tell us what you think! Please send any comments aboutthis article to [email protected] include the article title and author.

Sign up for the ITPro Today newsletter
Stay on top of the IT universe with commentary, news analysis, how-to's, and tips delivered to your inbox daily.

You May Also Like