Search code examples
c#asp.netrepeater

Nested Class In ASP Repeater


I have a nested class that contains order items for an order:

public class Order
{
  public int ItemID { get; set; }
  public int CustomerId { get; set; }
  ...
  public List<OrderItem> Items { get; set; }
}

public class OrderItem
{
  public int ItemId { get; set; }
  ...
}

and I have this databound to an asp repeater

var result = [method to get data]
rptOrders.DataSource = result;
rptOrders.DataBind();

and in the ascx page I have

<asp:Repeater ID="rptOrders" runat="server" HideControlForZeroRows="true" ZeroRowsText="You have no orders.">
<HeaderTemplate>
    <table>
        <tr class="tableHeader">
            <td>Order #</td>
            ...
        </tr>
</HeaderTemplate>
<ItemTemplate>
<ItemTemplate>
    <tr>
        <td><a href='#'><%# Eval("ItemID") %></a></td>
        ...
    </tr>
</ItemTemplate>

but I want to use an accordion to show hide the order details, an example is here: http://jsfiddle.net/Xqk3m/, which means I have to add rows to my repeater table for the nested class items.

How do I reference the nested class to have another repeater iterate over the elements to add a for each of the nested items?

I have looked around the web and generally they are suggesting that I have a nested repeater call the nested class separately but really I want to make use of the fact that I have well defined classes. Hopefully I can do something like:

//parent repeater
<asp:Repeater ID="rptOrders" runat="server" HideControlForZeroRows="true" ZeroRowsText="You have no orders.">
  ....
  //nested repeater
  <asp:Repeater ID="rptOrderItems" runat="server" HideControlForZeroRows="true">

but how can I reference the order items for the order?

        <asp:Repeater runat="server" DataSource="<%# Container.DataItem %>">
        <ItemTemplate>
            <tr>
                <td><%# Eval("ItemId") %></td>
            </tr>
        </ItemTemplate>
    </asp:Repeater>

Solution

  • You can add ItemDataBound event to rptOrders repeater:

    protected void rptOrders_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            var order = (Order)e.Item.DataItem;
    
            Repeater innerRep = e.Item.FindControl("rptOrderItems") as Repeater;
    
            innerRep.DataSource = order.Items;
            innerRep.DataBind();
        }
    

    In fact you can have any other data-bound control inside repeater item and bind it using list from DataItem.