Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access parent data in a nested strongly typed repeater

Lets say I have a class structure that looks something like this:

public class A
{
    public string Poperty1 { get; set; }
    public string Poperty2 { get; set; }
    public List<B> Property3 { get; set; }
}

public class B
{
    public string Property4 { get; set; }
    public string Property5 { get; set; }
}

...and a couple of nested repeaters that look like this:

<asp:Repeater ItemType="A" runat="server">
    <ItemTemplate>
        <asp:Label Text="<%# Item.Property1 %>" runat="server" />
        <asp:Repeater runat="server" DataSource="<%# Item.Property3 %>" ItemType="B">
            <ItemTemplate>
                <asp:Label Text="<%# Item.Property4 %>" runat="server" />
            </ItemTemplate>
        </asp:Repeater>
    </ItemTemplate>
</asp:Repeater>

How would I access Property2 from the second repeater?

like image 345
Douglas Ludlow Avatar asked May 02 '13 17:05

Douglas Ludlow


3 Answers

Well, from Accessing parent data in nested repeater, in the HeaderTemplate, I found the following solution. It's not the prettiest, but it works:

<%# ((Container.Parent.Parent as RepeaterItem).DataItem as A).Property2 %>
like image 117
Douglas Ludlow Avatar answered Oct 24 '22 16:10

Douglas Ludlow


You could use a generic Tuple as type for the inner repeater, and pass on the Item from the outer repeater:

<asp:Repeater ItemType="A" runat="server" ID="Rpt">
    <ItemTemplate>
        <asp:Label Text="<%# Item.Property1 %>" runat="server" />
        <asp:Repeater runat="server" 
            DataSource="<%#  Item.Property3.Select(innerItem => new Tuple<A,B>(Item, innerItem)) %>" 
            ItemType="System.Tuple<A,B>">
            <ItemTemplate>
                <asp:Label Text="<%# Item.Item2.Property4 %>" runat="server" />
            </ItemTemplate>
        </asp:Repeater>
    </ItemTemplate>
</asp:Repeater>

Be aware that ReSharper will protest against using generics in ItemType!

Here is a different example, closer to something I was working on:

<asp:Repeater runat="server" ID="RptWeekNumbers" ItemType="System.Int32">
    <ItemTemplate>
        <asp:Repeater runat="server" 
            DataSource="<%# Enumerable.Range(1, 5).Select(day => new Tuple<int,int>(Item, day))%>" 
            ItemType="System.Tuple<int,int>">
            <ItemTemplate>
                WeekNumber: <%# Item.Item1 %>, 
                DayNumber: <%# Item.Item2 %>
                <br />
            </ItemTemplate>
        </asp:Repeater>
    </ItemTemplate>
</asp:Repeater>
like image 20
andersh Avatar answered Oct 24 '22 14:10

andersh


When setting the DataSource for the inner repeater:

DataSource='<%# Eval("Property3") %>'

Note the single quote when setting the value.

like image 1
Gilberto Santos Avatar answered Oct 24 '22 16:10

Gilberto Santos