Programmatic templates

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

[csharp]
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;
}
}
}
[/csharp]

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s