The following steps will take us through to use the above
created MyTemplate class to create header, item and footer templates
dynamically.
1.
Create a 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 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];
dlArt.DataBind();
phArticles.Controls.Add(dlArt);
}
}
}
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 and now we will move on to the
implementation of dynamic GridView.