……………………………………………….Expertise in .NET Technologies

Creating Dynamic DataList control in C#/ASP.Net

Posted by Ravi Varma Thumati on October 23, 2009


In web applications, one the most common task is displaying a table of data to users. In ASP.Net 1.x, we make use of the Datagrid, DataList and Repeater controls. Every time, the need of displaying the data will be different. Sometimes, we will require the data to be displayed to the user where he/she should have edit/update/delete functionalities or we require displaying the data with the header being displayed in the left as opposed to top which makes us to decide which of the above control to use. Most of the time, it is sufficient if we drag the control into the webform instead of adding it dynamically to achieve the target.

At times, we will require doing this dynamically. This article will help us to create dynamic datalist control in ASP.Net.

Microsoft has designed this control in such a way that, it can be built dynamically by giving dynamic styles and layouts to the data display. Moving forward, I will explain a scenario where we can have a dynamic datalist control and how to construct it.

Sample Scenario

Consider, we are creating a site that hosts technical articles similar to CodeDigest.Com with the authors being submitting their article on different categories. Consider an article index page that displays top 4 articles on each category from the author’s submission. We can have a separate tabular view for each category in the article index page. Refer the below “Figure 1 – Article Listing” for clear understanding.

It will be hard and time consuming if we manually add a datalist for each new category added in the site. We can foresee the amount of difficulty we will face if we add a new datalist to the page manually whenever a new category is added and deploying it every time. In these situations, we can consider dynamically adding a datalist to serve the need without any manual efforts involved when a new category is added to the site. Thus we are preventing editing the page frequently for every new category and deploying it, but with a little overhead in development time as opposed to a static datalist.


Figure 1 – Article Listing

There can be many other scenarios like, when we are really not aware how many resultset a stored procedure is going to return which has dynamic queries generated depending upon some business rules. I will use the above example in this article to explain constructing dynamic Datalist control.

How to achieve it?

In precise, it can be done by implementing ITemplate interface in System.Web.UI namespace.

In this article, I will explain the construction of dynamic DataList control by building dynamic template columns. Moving forward, I will create dynamic template columns for DataList control specific to the resultset returned by the stored procedure. Template columns for datalist can be created by implementing the interface ITemplate in System.Web.UI namespace. Refer the code listing 1 and class diagram in figure 2 for ITemplate interface.

Listing 1 – ITemplate Interface

namespace System.Web.UI


// Summary:

//     Defines the behavior for populating a templated ASP.NET server control with

//     child controls. The child controls represent the inline templates defined

//     on the page.

public interface ITemplate


// Summary:

//     When implemented by a class, defines the System.Web.UI.Control object that

//     child controls and templates belong to. These child controls are in turn

//     defined within an inline template.


// Parameters:

//   container:

//     The System.Web.UI.Control object to contain the instances of controls from

//     the inline template.

void InstantiateIn(Control container);




Figure 2- ITemplate class diagram

With this information, we will now create header template, item template and footer template column for DataList control by implementing above ITemplate interface.

Steps for creating Template class

1.      Create a Template class (MyTemplate class, Listing 2 –TemplateClass for DataList) that implements ITemplate interface.

2.      Create a constructor for the class that takes ListItemType as argument so that we can determine whether we are constructing HeaderTemplate or ItemTemplate or FooterTemplate. Also we can make it through by exposing ListItemType as public property.

3.      Implement the InstantiateIn(Control container) method and construct the corresponding template from the input got from the constructor. Refer the code (Listing 2 –TemplateClass for DataList) for clear understanding.

4.      For data binding and child control that requires data binding, create a data binding event to fill the data with the control. This event will be raised after the template items are created with all its controls.

The above 4 steps have been implemented in the code, Listing 2 –TemplateClass for DataList.

Constructing Dynamic DataList

The DataList will have Header template with Category Name displayed. For example, if it is displaying ASP.Net article the category name will be ASP.Net. The articles will be displayed in the item template i.e. for every article in the item template we will display the title of the article as a hyperlink that links to the original URL of the article with a description and author name. The footer will show the number of articles present in this category. Refer “Figure 1 – Article Listing” for better understanding.

Listing 2 –TemplateClass for DataList

public class MyTemplate : ITemplate


ListItemType _itemType;

private string _no;

private string _categoryName;

public string NoOfArticles




return _no;




_no = value;



public string CategoryName




return _categoryName;




_categoryName = value;



public MyTemplate(ListItemType Type)


_itemType = Type;


public void InstantiateIn(System.Web.UI.Control container)


Literal lc = new Literal();

switch (_itemType)


case ListItemType.Header:

lc.Text = “<div id=\”nifty\” class=\”PostCategory\”>   ” + CategoryName + “</div>”;


case ListItemType.Item:

lc.DataBinding += new EventHandler(TemplateControl_DataBinding);


case ListItemType.Footer:

lc.Text = “<div style=\”text-align:right\”>” + NoOfArticles + ” Article(s)     present in this category” + “</div>”;





private void TemplateControl_DataBinding(object sender,  System.EventArgs e)


Literal lc;

lc = (Literal)sender;

DataListItem container = (DataListItem)lc.NamingContainer;

lc.Text += “<div class=\”Post\”><div class=\”PostTitle\”><A     href=” + DataBinder.Eval(container.DataItem, “URL”) + “>” + DataBinder.Eval(container.DataItem, “Title”) + “</a></div><div class=\”PostSubtitle\”>” + DataBinder.Eval(container.DataItem, “Description”) + “</div> <div class=\”PostInfo\”>Posted on ” + DataBinder.Eval(container.DataItem, “CreatedOn”, “{0:d} @ {0:t}”) + ” By ” + DataBinder.Eval(container.DataItem, “CreatedBy”) + ” in ” + DataBinder.Eval(container.DataItem, “Category”) + “</div> “;



In the above code (Listing 3 –TemplateClass for DataList), I have used 2 public properties, CategoryName and NoOfArticle, for displaying category name in Header Template and for displaying number of articles in Footer Template. We can also specify this as a constructor argument instead of giving as public properties. I have defined TemplateControl_DataBinding event to bind the data that is in resultset.

Using the Constructed Template Class in DataList

The following steps will take us through to use the above created MyTemplate class to create header, item and footer templates dynamically.

1.      Create DataList object.

2.      Create an instance of our created dynamic template class by passing the ListItemType corresponding to the type of the item.

3.      Assign the instance to the datalist template property like,

Listing 3 – DataList Templates

DataListObject.HeaderTemplate = new MyTemplate(ListItemType.Header);

DataListObject.ItemTemplate = new MyTemplate(ListItemType.Item);

DataListObject.FooterTemplate = new MyTemplate(ListItemType.Footer);

The below code (Listing 4- Using TemplateClass) contains code that uses the MyTemplate class to build the DataList dynamically. I have added a PlaceHolder in the Webform which will hold the dynamically created DataList after the execution.

Listing 4 –Using TemplateClass

protected void Page_Load(object sender, EventArgs e)


for (int i = 0; i < dsArticles.Tables.Count; i++)


if (dsArticles.Tables[i].Rows.Count > 0)


DataList dlArt = ConstructDL(dsArticles.Tables[i].Rows[0][“Category”].ToString(), dsArticles.Tables[i].Rows.Count);

dlArt.DataSource = dsArticles.Tables[i];






public DataList ConstructDL(string CategoryName,int Count)


DataList dlArt = new DataList();

MyTemplate headTemplate = new MyTemplate(ListItemType.Header);

headTemplate.CategoryName = CategoryName;

dlArt.HeaderTemplate = headTemplate;

dlArt.Width = Unit.Percentage(100);

dlArt.ItemTemplate = new MyTemplate(ListItemType.Item);

MyTemplate footerTemplate = new MyTemplate(ListItemType.Footer);

footerTemplate.NoOfArticles = Count.ToString();

dlArt.FooterTemplate = footerTemplate;

return dlArt;


In the above code, phArticles is the PlaceHolder id. Thus, we have created the DataList dynamically.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: