Programmatic templates
September 22nd, 2004 by alpriest
I’ve been musing for a while over how best to arrange the video links at the bottom of my gallery pages. For ages its just been a server control dumping them out as a table, but I thought tonight i’d try and change it to use a multi-column table instead.
This means using a DataList rather than handcoding, but from a server-side control, you can’t create the <itemTemplate> tags. Instead you to create a simple class that implements ITemplate and associate that. Code sample below, but after trawling the web I only found this one link of any use Dynamic Templates for the Repeater, DataList and DataGrid Controls
DataList dataList = new DataList();
dataList.DataSource = new string[] { "foo", "bar" };
dataList.ItemTemplate = new ShowLabelTemplate();
dataList.DataBind();
internal class ShowLabelTemplate : ITemplate
{
#region ITemplate Members
public void InstantiateIn(Control container)
{
Label l = new Label();
l.DataBinding += new EventHandler(this.LabelDataBinding);
container.Controls.Add(l);
}
#endregion
public void LabelDataBinding(object sender, EventArgs e)
{
Label l = (Label)sender;
if (l.NamingContainer is DataListItem)
{
DataListItem data = (DataListItem)l.NamingContainer;
l.Text = (string)data.DataItem;
}
}
}