There are three controls that use templates in ASP.NET (Repeater, DataList and DataGrid). You can create and use templates dynamically (in runtime) for each one of them.
You can choose one of two ways to do it:
- Create template as User Control (ascx) and load it dynamically using Page.LoadTemplate method. See Creating a Templated User Control.
- Implement ITemplate interface. This simple interface has single method InstantiateIn, which is responsible for rendering template content. Common pattern suggest passing template type (HeaderTemplate, ItemTemplate etc.) as constructor parameter. Simple template implementation could look like this:
public class SeverityTemplate : ITemplate
{
ListItemType templateType;
public SeverityTemplate(ListItemType type)
public SeverityTemplate(ListItemType type)
{
templateType = type;
}
public void InstantiateIn(System.Web.UI.Control container)
{
switch (templateType)
{
case ListItemType.Header:
Literal lc = new Literal();
lc.Text = "<U>Severity</U>";
container.Controls.Add(lc);
break;
case ListItemType.Item:
DropDownList ddl = new DropDownList();
ddl.Items.Add("High");
ddl.Items.Add("Medium");
ddl.Items.Add("Low");
ddl.DataBinding += new EventHandler(this.OnDataBinding);
container.Controls.Add(ddl);
break;
}
}
public void OnDataBinding(object sender, EventArgs e)
{
DropDownList ddl = (DropDownList) sender;
DataGridItem container = (DataGridItem) ddl.NamingContainer;
ddl.SelectedValue = ((DataRowView) container.DataItem)["Severity"].ToString();
}
}
Note There are some light differences in creating DataGrid Template columns (different template types). See Creating DataGrid Templates Programmatically.