The DataList will have a 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. 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.
Listing 2: TemplateClass for DataList
public class MyTemplate : ITemplate
{
ListItemType _itemType;
private string _no;
private string _categoryName;
public string NoOfArticles
{
get
{
return _no;
}
set
{
_no = value;
}
}
public string CategoryName
{
get
{
return _categoryName;
}
set
{
_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>";
break;
case ListItemType.Item:
lc.DataBinding += new EventHandler(TemplateControl_DataBinding);
break;
case ListItemType.Footer:
lc.Text = "<div style=\"text-align:right\">" + NoOfArticles
+ " Article(s) present in this category" + "</div>";
break;
}
container.Controls.Add(lc);
}
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 I have used 2 public properties,
CategoryName and NoOfArticle, for displaying category name in Header Template
and for displaying a number of articles in Footer Template. We can also specify
this as constructor argument instead of giving it as public properties. I have
defined TemplateControl_DataBinding event to bind the data that is in
resultset.