Search code examples
c#data-bindingrepeater

Bind a repeater dynamically inside another repeater?


I have this code:

<asp:Repeater id="repeaterCategories" runat="server">
    <ItemTemplate>
        <div class="categorie-item">
            ...

            <asp:Repeater id="repeaterSubCategories" runat="server">
                <ItemTemplate>
                    ...
                </ItemTemplate>
            </asp:Repeater>
        </div>                    
    </ItemTemplate>
</asp:Repeater>

and repeaterSubCategories must be repeaterCategories.SubCategories, for each repeaterCategories. So I have to bind dynamically (for each first repeater iteration) a list of sub categories.

Can I do it? How?


Solution

  • If you have a nested repeater like this:

    <asp:Repeater ID="Repeater1" runat="server" OnItemDataBound="Repeater1_ItemDataBound">
        <ItemTemplate>
            <asp:Repeater ID="Repeater2" runat="server"></asp:Repeater>
        </ItemTemplate>
    </asp:Repeater>
    

    You can use this to bind to it:

    protected void Repeater1_ItemDataBound(object sender, RepeaterItemEventArgs e)
    {
        var data = ((MyClass)e.Item.DataItem).Subcategories;
        var repeater2 = (Repeater)e.Item.FindControl("Repeater2");
        repeater2.DataSource = data;
        repeater2.DataBind();
    }