Consider we are creating a site that hosts technical
articles similar to aspalliance.com/Codeproject.com with the authors submitting
their article on different categories. Consider an article index page that
displays the 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 to the below "Figure 1 – Article Listing" for a clear
It will be hard and time consuming if we manually add a GridView/DataList
for each new category added in the site. We can feel the difficulty if we add a
new GridView/DataList to the page manually whenever a new category is added to
the site and deploy it again. In this situation we can consider dynamically
adding a GridView/DataList to serve the need without any manual efforts
involved when a new category is added to the site. Therefore, we are preventing
editing the page frequently for every new category and deploying it, with only a
little overhead in development time as opposed to a static GridView/DataList.
Figure 1: Article Listing
There can be many other scenarios like, when we really do
not know how many resultset a stored procedure is going to return that has
dynamic queries depending upon some business rules. I will use the above
example of article site throughout this article to explain constructing dynamic
How to achieve it?
It is achieved by implementing ITemplate interface in
In this article I will explain the construction of dynamic
DataList and GridView by building dynamic template columns. Moving forward I
will create dynamic template columns for both Datalist and gridview specifically
the resultset returned by the stored procedure. Template columns for both
datalist and gridview can be created by implementing the interface ITemplate in
System.Web.UI namespace. Refer to Listing 1 and class diagram in Figure 2 for
Listing 1: ITemplate Interface
// 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
// 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.
// 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 these controls by implementing the
above ITemplate interface.