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:
public class FibonacciControl : CompositeControl
{
public FibonacciControl()
{
// ....
}
protected override void CreateChildControls()
{
base.CreateChildControls();
ListView view = new ListView();
view.LayoutTemplate = new LayoutTemplate();
view.ItemTemplate = new ItemTemplate();
view.DataSource = FibonacciSequence();
view.DataBind();
this.Controls.Add(view);
}
private IEnumerable<int> FibonacciSequence()
{
int i1 = 0;
int i2 = 1;
for (int i = 0; i < Iterations; i++)
{
yield return i1 + i2;
int temp = i1 + i2;
i1 = i2;
i2 = temp;
}
yield break;
}
public int Iterations { get; set; }
private class LayoutTemplate : ITemplate
{
public void InstantiateIn(Control container)
{
var ol = new HtmlGenericControl("ol");
var li = new HtmlGenericControl("li") { ID = "itemPlaceholder" };
ol.Controls.Add(li);
container.Controls.Add(ol);
}
}
private class ItemTemplate : ITemplate
{
public void InstantiateIn(Control container)
{
var li = new HtmlGenericControl("li");
li.DataBinding += DataBinding;
container.Controls.Add(li);
}
public void DataBinding(object sender, EventArgs e)
{
var container = (HtmlGenericControl)sender;
var dataItem = ((ListViewDataItem)container.NamingContainer).DataItem;
container.Controls.Add( new Literal(){Text = dataItem.ToString() });
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With