Blue Theme Orange Theme Green Theme Red Theme
 
Home | Forums | Videos | Photos | Blogs | Beginners
 | Consulting  
Submit an Article Submit a Blog 
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
 Resources  
Close
 Our Network  
Close
Search :       Advanced Search »
Home » ASP.NET and Web » Programming Template in Web Server Controls

Programming Template in Web Server Controls


Templates play a major role in managing the layout and format of the data being displayed in ASP.NET data bound controls.

Author Rank:
Total page views :  6618
Total downloads : 
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
 
Become a Sponsor

When developing Windows and Web GUI applications, it's impossible to resist the use of data-bound controls. Fortunately, both Windows Forms and Web Forms provide a rich set of data-bound controls that can be used to write a variety of data-driven applications. 

Data-bound controls are not only used to display data from data source, they can also be used to represent data in different formats by managing data-bound controls' layout. In Web server data-bound controls, templates can be used to manage the format and layout of data being displayed in the pages.
 
Introduction.

Templates play a major role in managing the layout and format of the data being displayed in ASP.NET data bound controls. Before we use templates in our application, let's take a quick look at template basics and how to they work.

Templates provide a way to apply a complex formatting on a control's parts such as header, footer, and items. A template is a set of HTML tags, which defines the layout for a particular part of a control. Besides HTML tags, a template can also contain  other controls and ASP.NET inline code.

OK, to have a better understanding, let's take a look at a simple use of templates. The code listed in Listing 1 uses templates in a Repeater control. As you can see from this code listing, I'm using AlternatingTemplate and ItemTempate templates. I'm going to discuss different types of templates in the following section. In AlternatingTemplate, I set font color = red, face = verdana and size = 3 and in ItemTemplate, I use color = green, face = Tahoma, and size = 2. I'm also using HTML table control to display items. You probably can guess from this code. The items of a repeater control will have green color, face Tahoma with size 2. Alternating rows and its items will have color red, face verdana, and size 3.

Listing 1. Applying a simple template on a Repeater control.

<ASP:Repeater id="repeaterControl" runat="server">
<AlternatingItemTemplate>

<font color="red" face = "verdana" size =
3>
<
table
>
<
tr>alternating data</tr
>
</
table
>
</
font>

</AlternatingItemTemplate
>
<
ItemTemplate
>
<
font color="green" face = "tahoma" size =
2>
<
table
>
<
tr>some item</tr
>
</
table
>
</
font>

</ItemTemplate
>
<
FooterTemplate
>
</
FooterTemplate>

</ASP:Repeater></P>

Template Types.

A template describes the layout and formatting of a part of a control. Similar to other control tags, templates also have a starting and ending pair of tags. For example, HeaderTemplate describes the layout and format of header of a control. The <HeaderTemplate></HeaderTemplate> pair represents a header template of a control. There are many types of templates as described below.

Table 1 describes the available templates.

Table 1. ASP.NET Templates.

Template Description
HeaderTemplate Describes the layout and format of the header of a control
FooterTemplate Describes the layout and format of the footer of a control.
ItemTemplate Describes the layout and format of the items displayed by a control.
AlternatingItemTemplate Describes the layout and format of alternating items of a control.
SeparatorTemplate A separator separates two items of a control. The SeparatorTemplate describes the layout and format of separator of a control.
SelectedItemTemplate Describes the layout and format of selected items of a control.
EditItemTemplate Some controls such as a DataGrid allows users to edit items. The    EditItemTemplate describes the layout and format of the items that are being edited.
Pager template DataGrid control allows users to have a paging option through the pager. The Pager template describes the layout and format of the pager of DataGrid.

Which Controls Support Templates?

Templates are not supported by all ASP.NET data-bound controls. Templates are supported by complex controls only. In addition to that, each control supports a different set of templates that specify layouts for different portions of the control, such as the header, footer, item, and selected item. The Repeater, DataList, and DataGrid are the controls, which utilize templates.

The Repeater control supports HeaderTemplate, FooterTemplate, ItemTemplate, AlternatingItemTemplate, SeperatorTemplate.

The DataList control supports HeaderTemplate, FooterTemplate, ItemTemplate, AlternatingItemTemplate, SeparatorTemplate, SelectedItemTemplate, and EditItemTemplate.

The DataGrid supports HeaderTemplate, FooterTemplate, ItemTemplate, EditItemTemplate, and Pager.

Creating Templates.

You can create templates using template tags by simply editing your aspx page in a text editor or HTML view of VS.NET.

In Listing 1, we saw you can easily create and use templates in an ASP.NET page by simply defining template tags and have the formatting layout inside the tags. For example, say you want to add templates to a DataList control. First of all, you need to find out what templates do you want to use. A DataList control supports header, footer, item, alternating item, selected item, and edit item templates.

Now let's say we want to use header, item, alternating item and footer templates. The code listed in Listing 2 adds header, item, alternating item, and footer templates of a DataList control. The RepeateColumns property of DataList represents how many column a row of DataList can display.

Listing 2. Adding templates to a DataList control.

<ASP:DataList id="dtList" RepeatColumns="5" RepeatDirection="Horizontal" runat="server">
<
HeaderTemplate>
</
HeaderTemplate>
<
AlternatingItemTemplate>
</
AlternatingItemTemplate>
<
ItemTemplate>
</
ItemTemplate>
<
FooterTemplate>
</
FooterTemplate>
</
ASP: DataList > 

So far the code would do nothing. Now we need to add the format of the template within the template tags. The code listed in Listing 3 adds contents to the templates of a DataList control. As you can see from this code, header, footer, item, alternating item templates has different format. You can make this format as much as complex you want. You can even add Web controls to these templates.

Listing 3. Adding templates format of a DataList control.

<HeaderTemplate>
<
font color = #cc3333 face ="verdana" size = 3>
<b>DataList Control Header</b>
</
font>
</
HeaderTemplate>
<
AlternatingItemTemplate>
<
font face ="verdana" size = 2 color ="green" >
<
br>
<
b>Category ID: </b><%# DataBinder.Eval(Container.DataItem, "CategoryID") %><br>
<
b>Category Name: </b><%# DataBinder.Eval(Container.DataItem, "CategoryName")%><br>
<
b>Description: </b><%# DataBinder.Eval(Container.DataItem, "Description") %><br>
<
b>Picture: </b><%# DataBinder.Eval(Container.DataItem, "Picture") %><p>
</
div>
</
font>
</
AlternatingItemTemplate>
<
ItemTemplate>
<
font face ="verdana" size = 2>
<
br>
<
b>Category ID: </b><%# DataBinder.Eval(Container.DataItem, "CategoryID") %><br>
<
b>Category Name: </b><%# DataBinder.Eval(Container.DataItem, "CategoryName")%><br>
<
b>Description: </b><%# DataBinder.Eval(Container.DataItem, "Description") %><br>
<
b>Picture: </b><%# DataBinder.Eval(Container.DataItem, "Picture") %><p>
</
div>
</
font>
</
ItemTemplate>
<
FooterTemplate>
<
font color= #996600 face ="verdana" size = 1>
DataList Control footer
</font>
</
FooterTemplate>

Templates in Action.

OK, now let's use templates. In our sample, I'm going to use a DataList control. The complete code of aspx page is listed in Listing 4. The asp:DataList syntax represents a DataList server control in ASP.NET. The RepeateColumn property of DataList represents the number of columns we want to display in a row of DataList. 

In this sample, we've a method called FillData. This method binds data from Northwind SQL Server database to the DataList control.

Listing 4. 

<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.SqlClient" %>

<HTML>
<
BODY>
<
font color="#006699" size="4" face="verdana">
DataList Server Control Sample </font>
<
script language="VB" runat="server">
Sub
Page_Load(sender As Object, e As EventArgs)
fillData()
End SUb
sub
fillData()
Dim conn As SqlConnection
Dim adapter As SqlDataAdapter
dim connectionString = "Data Source=MCB;Initial Catalog=Northwind;user id=sa;password=;" conn = new SqlConnection(connectionString)
conn.Open()
dim sql = "SELECT * FROM Categories"
adapter =
new SqlDataAdapter(sql, conn)
Dim ds As Dataset = new DataSet()
adapter.Fill(ds)
dtList.DataSource = ds
dtList.DataBind()
end sub
</
script>
<
P>
<
ASP:DataList id="dtList" RepeatColumns="5" RepeatDirection="vertical" runat="server">
<
HeaderTemplate>
<
FONT face="verdana" color="#cc3333" size="3">
<
B>DataList Control Header</B> </FONT>
</
HeaderTemplate>
<
FooterTemplate>
<
FONT face="verdana" color="#996600" size="1">DataList Control footer </FONT>
</
FooterTemplate>
<
ItemTemplate>
<
FONT face="verdana" size="2">
<
BR>
<
B>Category ID: </B><%# DataBinder.Eval(Container.DataItem, "CategoryID") %><BR>
<
B>Category Name: </B><%# DataBinder.Eval(Container.DataItem, "CategoryName")%><BR>
<
B>Description: </B><%# DataBinder.Eval(Container.DataItem, "Description") %><BR>
<
B>Picture: </B><%# DataBinder.Eval(Container.DataItem, "Picture") %><P>
</
FONT>
</
ItemTemplate>
<
AlternatingItemTemplate>
<
FONT face="verdana" color="green" size="2">
<
BR><B>Category ID: </B><%# DataBinder.Eval(Container.DataItem, "CategoryID") %><BR>
<
B>Category Name: </B><%# DataBinder.Eval(Container.DataItem, "CategoryName")%><BR>
<
B>Description: </B><%# DataBinder.Eval(Container.DataItem, "Description") %><BR>
<
B>Picture: </B><%# DataBinder.Eval(Container.DataItem, "Picture") %><P>
<
DIV></DIV>
</
FONT>
</
AlternatingItemTemplate>
</
ASP:DataList>
</
P>
</
BODY>
</
HTML> 

The output of Listing 4 is shown in Figure 1, where you can see that data from Categories table of Northwind database is displayed.

How to Compile the Code?

If you're using VS.NET IDE, create a Web application project, open aspx page and copy the entire code. If you're using a text editor, simply copy code in a text editor and save file with aspx extension. 

You also need to change the SQL Server name, user id, and password in the connection string.

Conclusion.

In this article, I discussed some basics of templates and how to use them in data-bound server controls to format the layout of data being displayed in the controls. In my next article, I'll explore the functionality of a DataList control in more details and how to write interactive Web applications using a DataList control.


Login to add your contents and source code to this article
 About the author
 
Mahesh Chand
Mahesh is a software developer with over 13 years of experience building systems for Financial and Banking, Engineering & Architectural, Imaging, Construction, Biological & Pharmaceuticals, Healthcare and Education industries. His expertise is Windows Forms, ASP.NET, Silverlight, WPF, WCF, Visual Studio 2010, SQL Server, and Oracle. If you are looking for a Sharepoint, Windows Forms, ASP.NET, WPF, Silverlight, C#, VB.NET, Oracle, and SQL Server Consultant in Philadelphia area or remote location, drop me a line at MAHESH [AT] C-SHARPCORNER [DOT] COM.
Looking for C# Consulting?
C# Consulting is founded in 2002 by the founders of C# Corner. Unlike a traditional consulting company, our consultants are well-known experts in .NET and many of them are MVPs, authors, and trainers. We specialize in Microsoft .NET development and utilize Agile Development and Extreme Programming practices to provide fast pace quick turnaround results. Our software development model is a mix of Agile Development, traditional SDLC, and Waterfall models.
Click here to learn more about C# Consulting.
 
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
Dynamic PDF
ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
SQL and .NET performance profiling in one place
Investigate SQL and .NET code side-by-side with ANTS Performance Profiler 6, so you can see which is causing the problem without switching tools.
Go.NET
Build custom interactive diagrams, network, workflow editors, flowcharts, or software design tools. Includes many predefined kinds of nodes, links, and basic shapes. Supports layers, scrolling, zooming, selection, drag-and-drop, clipboard, in-place editing, tooltips, grids, printing, overview window, palette. 100% implemented in C# as a managed .NET Control. Document/View/Tool architecture with many properties&events. Optional automatic layout.
Dundas Software
Dundas Chart for .NET is the most advanced .NET charting package available today.  With an extremely complete feature set, elegant architecture and easy implementation, Dundas Chart can quickly add advanced Charting functionality to enhance and transform ASP.NET and Windows Forms applications.  Whether you are implementing charting into internal projects, or building applications for clients, Dundas Chart offers advanced technology and advanced results to get the most out of data.
60 FREE UI Controls from DevExpress
Register for your FREE copy on over 60 free presentation controls from DevExpress - Absolutely Free-of-Charge without any royalties or distribution costs. Visit Devexpress.com/60 today. Free controls include advanced lists box, dropdown calendar, rich text edit, spin edit, tab control and so much more!

DevExpress engineers feature rich presentation controls and reporting tools for WinForms, ASP.NET, WPF, and Silverlight. Our technologies help you build your best, see complex software with greater clarity and deliver compelling business solutions for Windows and the web in the shortest possible time.
Clickatell's SMS Gateway
Clickatell's Developer Solutions allow you to SMS enable any website or application via a range of API's. Learn More about our API connections.
Free access to .NET Memory Management video
Everything you need to know about Garbage Collection, Temporary Objects, Fragmentation, Finalization and common causes of memory leaks in .NET. Watch the video here.
Microsoft Visual Studio 2010
Visualize your workspace with new multiple monitor support, powerful Web development, new SharePoint support with tons of templates and Web parts, and more accurate targeting of any version of the .NET Framework. Get set to unleash your creativity.
Nevron Chart for .NET 2010.1 Now Available
The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
Developer-Ready ASP.NET 2.0 Web Hosting with 3 MONTHS FREE
Now supporting .NET 3.0 Framework with Windows Workflow Foundation, Windows Communication Foundation (WCF), Windows Presentation Foundation (WPF), windows CardSpace (WCS)! Providing more flexibility for Developers with Web Services Support and a User/Permission Manger. Also supporting MS SQL 2005/2000 with Real-Time Backups, FREE Automated Attach .MDF Tool, FREE SQL Restore and Shrink SQL DB Tools, and SQL
Read the Top 10 Books for Microsoft Developers, 15 Days FREE
Read the Top 10 Books for Microsoft Developers, 15 Days FREE
Try Safari Books Online - 15 Days FREE + 15% Off for 1 Year
Try Safari Books Online - 15 Days FREE + 15% Off for 1 Year
 
 Post a Feedback, Comment, or Question about this article
Subject:
Comment:
Nevron Chart
Become a Sponsor
 Comments

 Hosted by MaximumASP  |  Found a broken link?  |  Contact Us  |  Terms & conditions  |  Privacy Policy  |  Site Map  |  Suggest an Idea  |  Media Kit
Current Version: 5.2010.8.14
 © 2010  contents copyright of their authors. Rest everything copyright Mindcracker. All rights reserved.