I am writing a Composite control, which contains a listview to display a table of items. Normally when using a ListView in Asp.NET I would define the templates in the code-forward.
<asp:ListView runat='server' ID='ArticleList'> <LayoutTemplate> <div class='ContentContainer'> <div runat='server' id='itemPlaceholder' /> </div> </LayoutTemplate> <ItemTemplate> <div> <div><%# Eval('Content') %></div> </div> </ItemTemplate> </asp:ListView>
I assume it’s something like:
ListView view = new ListView(); view.LayoutTemplate = ..... view.ItemTemplate = ..... // when do I call these? view.DataSource = myDataSource; view.DataBind();
Update: I created 2 templates by implementing the ITemplate interface:
private class LayoutTemplate : ITemplate { public void InstantiateIn(Control container) { var outer = new HtmlGenericControl('div'); var inner = new HtmlGenericControl('div') { ID = 'itemPlaceholder' }; table.Rows.Add(row); container.Controls.Add(table); } } private class ItemTemplate : ITemplate { public void InstantiateIn(Control container) { var inner = new HtmlGenericControl('div'); container.Controls.Add(inner); } }
and I can add them using:
dataList.LayoutTemplate = new LayoutTemplate(); dataList.ItemTemplate = new ItemTemplate();
But then I get stuck, since container.DataItem is null.
The trick is to subscribe to the databinding event of the itemplaceholder in the ItemTemplate.
The complete solution: