Blue Theme Orange Theme Green Theme Red Theme
 
Home | Forums | ASP.NET 2.0 Tutorials | Web Services | How Do I...? | Class Browser | WPF Quick Starts | Advertise with Us
 | Consulting  
Submit an Article Submit a Blog 
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
6 Months Free & No Setup Fees ASP.NET Hosting!
Search :       Advanced Search »
Home » Server Controls » Loading ASP.NET Templates Dynamically

Loading ASP.NET Templates Dynamically

There are occasions when programmers needs to load templates dynamically. In this article, I will show you how to load ASP.NET templates dynamically for a DataList Web server controls based on the user selection.

Author Rank :
Page Views : 22495
Downloads : 314
Rating :
 Rate it
Level : Beginner
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
Download Files:
DynamicTemplates.zip
 
 
6 Months Free & No Setup Fees ASP.NET Hosting!
Become a Sponsor
Become a Sponsor
 Tag Cloud
 Latest Jobs
More ... 
 Latest Interview Questions
More ... 

There are occasions when programmers needs to load templates dynamically. For example, when you want to change the format of your application based on the user, you can simply manage multiple templates and load dynamically based on the user. Here you need to be cautious about templates because all Web controls don't support templates and some of the Web controls support only selected templates. In this article, I will show you how to load ASP.NET templates dynamically for a DataList Web server controls based on the user selection.

The Concept

To understand the template load procedure, we need to go to the TemplateControl class. The TemplateControl class is the base class for Page and UserControl classes. It also defines the base functionality for Page and UserControl classes. This class provides two methods - LoadControl and LoadTemplate. The LoadControl method loads a user control from an external file and returns a UserControl object. The LoadTemplates loads a template from an external file and returns an object of ITemplate.

As I said earlier, the Page class is derived from the TemplateControl and the Page object represents an ASP.NET Web page. Hence TemplateControl functionality is also available through the Page class. To load external templates, we will use the LoadTemplate method of TemplateControl through the Page object.

The LoadTemplate method takes a single argument of the external template file name with full path and returns an ITemplate object. The DataList control provides properties that can be used to set the templates. The DataList class provides the AlternatingItemTemplate, EditItemTemplate, FooterTemplate, HeaderTemplate, ItemTemplate, SelectedItemTemplate, and SeperatorTemplate properties.

The Data

In this article, I will create a DataSet in memory and will use that DataSet to fill a DataList control. The code listed in Listing 1 shows the DB class. The GetDataSet method of this class creates and returns a DataSet object.

Listing 1. The DB class

public class DB
{
public DB()
{
}
/// <summary>
/// Method returns a DataSet object filled with data
/// </summary>
public static DataSet GetDataSet()
{
// Create a DataSet and a DataTable
DataSet ds = new DataSet();
DataTable table =
new DataTable("Records");
DataColumn col;
// Create & Add DataTable columns
col = new DataColumn();
col.DataType = System.Type.GetType("System.Int32");
col.ColumnName = "ID";
col.ReadOnly =
true;
col.Unique =
true;
table.Columns.Add(col);
col =
new DataColumn();
col.DataType = System.Type.GetType("System.String");
col.ColumnName = "Name";
col.AutoIncrement =
false;
col.Caption = "Name";
col.ReadOnly =
false;
col.Unique =
false;
table.Columns.Add(col);
col = new DataColumn();
col.DataType = System.Type.GetType("System.String");
col.ColumnName = "Address";
col.AutoIncrement =
false;
col.Caption = "Address";
col.ReadOnly =
false;
col.Unique =
false;
table.Columns.Add(col);
// Create & Add DataTable rows
DataRow row = table.NewRow();
row["ID"] = 1001;
row["Name"] = "Melanie Giard";
row["Address"] = "23rd Street, Park Road, NY City, NY";
table.Rows.Add(row);
row = table.NewRow();
row["ID"] = 1002;
row["Name"] = "Puneet Nehra";
row["Address"] = "3rd Blvd, Ashok Vihar, New Delhi";
table.Rows.Add(row);
row = table.NewRow();
row["ID"] = 1003;
row["Name"] = "Raj Mehta";
row["Address"] = "Nagrath Chowk, Jabalpur";
table.Rows.Add(row);
row = table.NewRow();
row["ID"] = 1004;
row["Name"] = "Max Muller";
row["Address"] = "25 North Street, Hernigton, Russia";
table.Rows.Add(row);
// Add DataTable to DataSet
ds.Tables.Add(table);
// Return DataSet
return ds;
}
}

In this application, I will be using GetDataSet method to get a DataSet object and bind it to the DataList control.

The Templates

Before we create our application, we need to create the templates. In this application, I will use four templates - footer, header, item, and alternating item. Actually, I have two groups of templates. Each group has four templates for header, footer, item, and alternating item. A typical item template looks like Listing 2. The source code listed in Listing 2 is stored in an ascx file called ItemTemplate.ascx. Similar to this file, I have ascx files for other templates.

Listing 2. A typical item template

<%@ Language = "VB" %>
<FONT face="verdana" color="red" size="2"><b>ID: </b>
       <%# DataBinder.Eval(CType(Container, DataListItem).DataItem, "ID") %>
       <b>Name: </b>
       <%# DataBinder.Eval(CType(Container, DataListItem).DataItem, "Name") %>
       <br>
       <b>Address: </b>
       <%# DataBinder.Eval(CType(Container, DataListItem).DataItem, "Address") %>
       <p>
</FONT>

Similar to the item template listed in Listing 2, I have eight templates. See the attached source code for more details.

The Application

Now the last step is to create an application. To test this, I create a Web application, add a DataList control, two Button controls on a Panel. The final Web page looks like Figure 1.

 

Now we create a method, BindDataGrid, which binds a DataSet to the DataList control. The BindDataGrid method is listed in Listing 3. 

Listing 3. The BindDataGrid method 

// This methods binds a DataSet to the DataGrid
private void BindDataGrid()
{
// DB.GetDataSet returns a DataSet with a table
// called 'Records' with three columns - ID, Name and Address
dtSet = DB.GetDataSet();
DataList1.DataSource = dtSet.Tables[0].DefaultView;
DataList1.DataBind();
}

We call
this method on the page load as shown below -

private void Page_Load(object sender, System.EventArgs e)
{
if(!IsPostBack)
{
BindDataGrid();
}
}

In the last step of this article, we add code for two button click event handlers. On these button click event handlers, we load two different templates. As you can see from this code, I set the DataList’s AlternatingItemTemplate, ItemTemplate, HeaderTemplate, and FooterTemplate properties by using the Page.LoadTemplate method. 

private void Button1_Click(object sender, System.EventArgs e)
{
// Load templates
DataList1.AlternatingItemTemplate = Page.LoadTemplate("AltItemTempate.ascx");
DataList1.ItemTemplate =Page.LoadTemplate("ItemTemplate.ascx");
DataList1.HeaderTemplate =Page.LoadTemplate("HeadTemplate.ascx");
DataList1.FooterTemplate = Page.LoadTemplate("FootTemplate.ascx");
BindDataGrid();
}
private void Button2_Click(object sender, System.EventArgs e)
{
// Load templates
DataList1.AlternatingItemTemplate =
Page.LoadTemplate("AltItemTempate2.ascx");
DataList1.ItemTemplate = Page.LoadTemplate("ItemTemplate2.ascx");
DataList1.HeaderTemplate = Page.LoadTemplate("HeadTemplate2.ascx");
DataList1.FooterTemplate = Page.LoadTemplate("FootTemplate2.ascx");
BindDataGrid();
}

Now if you run the application and click on the button 1, the output looks like Figure 2.

 

Click on the button 2 generates the output that looks like Figure 3. 

 

Conclusion 

ASP.NET templates are useful in formatting data-bound controls. In this chapter, I showed you how to load templates dynamically. Using the same procedure, you can use the same application to display data in different format depending on the user settings.

Comment Request!
Thank you for reading this post. Please post your feedback, question, or comments about this post Here.
Login to add your contents and source code to this article
 [Top] Rate this article
 
 About the author
 
Mahesh Chand
Mahesh is the founder of C# Corner and Mindcracker Network, an author of several .NET programming books and a Microsoft MVP for 6 consecutive years. In his day to day work, Mahesh is a Senior Software Consultant with over 14 years of IT industry 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.
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.
ASP.NET 4 Hosting
Get 2 Months Free of ASP.NET Hosting for Only $4.95/month! Receive FREE MS SQL and MySQL Databases Including ASP.NET 4/3.5, MVC 3.0, Silverlight 4, Windows 2008/IIS 7.0 Plus FREE IIS 7 Modules. Host UNLIMITED ASP.NET Web Sites – Click Here!
 
 Post a Feedback, Comment, or Question about this article
Subject:
Comment:
Nevron Gauge for SharePoint
Become a Sponsor
 Comments
Team Foundation Server Hosting
 © 2012  contents copyright of their authors. Rest everything copyright Mindcracker. All rights reserved.