Nested repeaters - accessing a control inside the parent repeater from the child repeater
I have a page where I list several hotels, and for each hotel I list the prices for each date that the user selected.
My HTML looks like this:
<table>
<asp:Repeater ID="rptrHotels" runat="server">
<ItemTemplate>
<tr><td><%# Eval("HotelName") %></td></tr>
<tr>
<asp:Repeater ID="rptrHotelRates" runat="server" DataSource='<%# GetHotelRates(Container.DataItem) %>'>
<ItemTemplate>
<td>
<span class="date"><%# Eval("Date") %></span>
<span class="price">$<%# Eval("Price") %></span>
</td>
</ItemTemplate>
</asp:Repeater>
<td>
<span class="date">Total</span>
<span class="price">$<asp:Literal ID="litTotal" runat="server" /></span>
</开发者_StackOverflowtd>
</tr>
</ItemTemplate>
</asp:Repeater>
</table>
And my code-behind:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
DateTime startDate = Request.QueryString["StartDate"];
DateTime endDate = Request.QueryString["EndDate"];
List<Hotel> hotels = GetHotels(startDate, endDate);
rptrHotels.DataSource = hotels;
rptrHotels.DataBind();
}
}
protected List<Rate> GetHotelRates(object item)
{
DateTime startDate = Request.QueryString["StartDate"];
DateTime endDate = Request.QueryString["EndDate"];
Hotel hotel = (Hotel)item;
List<Rate> rates = GetRates(hotel, startDate, endDate);
decimal total = (from r in rates
select r.Price).Sum();
return rates;
}
In my GetHotelRates() function, I'm getting the total price by summing up all the rate prices. But I need to somehow put that value in litTotal, which is outside the child repeater, but inside the parent repeater.
How can I do that?
In your item binding event do something like this:
((Literal)((Repeater)sender).Parent.FindControl("litTotal")).Text;
You might need to do another cast on the parent to get it to a Repeater, but I'm not sure.
You could always try some NamingContainer.Parent.Parent....FindControl (exaggerated) magic, but a cleaner way to do it would be to just create a separate method to get your total:
protected decimal GetHotelTotal(object item)
{
Hotel hotel = (Hotel)item;
List<Rate> rates = GetRates(hotel, startDate, endDate);
decimal total = (from r in rates
select r.Price).Sum();
return total;
}
And call this in your Literal:
<asp:Literal ID="litTotal" runat="server" Text="<%# GetHotelTotal(Container.DataItem) %>" />
精彩评论