I have been using repeaters to bind a nested collection. Basically what I am doing is, display all the elements & values in WebPage.
My approach has been, to use nested repeaters and bind a level below repeater datasource in current ItemDataBount Event (please refer code below)
It is a lot of copy & paste task to create controls for each & every item and bind that data using Eval.
Considering the fact that DataSource is serializable, Is this efficient & simplest way to Bind Nested Collections ?
<asp:Repeater ID="rpt1" OnItemDataBound="rpt1_ItemDataBound" runat="server">
<ItemTemplate>
<asp:Label ID="lblSomeProperty" Text='<%#Eval("SomeProperty") %>' runat="server" />
<%--few other controls--%>
<asp:Repeater ID="rpt2"OnItemDataBound="rpt2_ItemDataBound" runat="server">
<ItemTemplate>
<asp:Label ID="Label1" Text='<%#Eval("SomeOtherProperty") %>' runat="server" />
<asp:Repeater ID="rpt3" runat="server">
<ItemTemplate>
<asp:Label ID="Label1" Text='<%#Eval("SomeMoreProperty") %>' runat="server" />
</ItemTemplate>
</asp:Repeater>
</ItemTemplate>
</asp:Repeater>
</ItemTemplate>
</asp:Repeater>
CodeBehind:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
rpt1.DataSource = //RootElement IEnumerable
}
}
protected void rpt1_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
//proceed only if ItemTemplate OR AlternatingItemTemplate
//populate user control values from DataItem in current context
var rpt2 = e.Item.FindControl("rpt2") as Repeater;
rpt2.DataSource = //Child Level1 IEnumerable
}
protected void rpt2_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
//bind rpt3 DataSource
}
Thank you for your help.
If the datasource is serializable then you should definitely consider using ListViews (MSDN) instead of Repeaters to display your data. Using ListViews, you can bind the datasource declaratively and not need to write any code-behind. You would be able to effectively eliminate all of the C# code you’re using to bind each repeater.
Take a look at this StackOverflow answer for a detailed explanation as to how to do this.
The key is to set the DataSource in the markup within each nested ListView