views:

298

answers:

1

If I have a nested ListView, and I'm calling a related table in LinQ, how do I sort it, without resorting to the ItemDataBound event of the parent?

Pseudo Code (UPDATED WITH SOLUTION):

<asp:ListView ID="lv" runat="server" OnItemDataBound="lv_ItemDataBound" >
   <LayoutTemplate>
      <!-- Product Category Stuff --> 
      <asp:PlaceHolder Id="itemPlaceholder" runat="server"></asp:PlaceHolder>
   </LayoutTemplate>

   <ItemTemplate>
      <asp:ListView ID="lvInner" runat="server" DataSource='<%# <%# ((Category)Container.DataItem).Products.OrderBy(p => p.Description) %> %>'>
         <LayoutTemplate>
            <ul>
               <asp:PlaceHolder ID="itemPlaceholder" runat="server"></asp:PlaceHolder>
            </ul>
         </LayoutTemplate>
         <ItemTemplate>
            <li>Item Stuff</li>
         </ItemTemplate>
      </asp:ListView>
   </ItemTemplate>
</asp:ListView>

Perhaps the method is deceptively simple, but I want the inner Products to be sorted by a field. I can't see a way to do it declaratively as LinQ creates this Query on the fly, if I'm not mistaken, and doesn't do sorting.

Any thoughts?

UPDATE

Updated the Example to the following:

<%# ((Category)Container.DataItem).Products.OrderBy(p => p.Description) %>

Hope it helps someone else!

+5  A: 

My assumption is that Products is an IEnumerable<Product> (or IQueryable). If that is the case, why not just add the OrderBy method to the evaluation, like so:

<%# Eval("Products.OrderBy(p => p.FieldToSortOn)") %>
casperOne
This may sound stupid... but I didn't even think of that... or to be more accurate... I didn't realize you could do that. Thanks. Testing now.
Atømix
On second glance, this doesn't seem possible. Can I really Use Eval to evaluate a String Expression? I get this error: DataBinding: 'OrderBy(p => p' is not a valid indexed expression.
Atømix
GOT IT! Same idea, but I did it the following way:<%# ((Category)Container.DataItem).Products.OrderBy(p => p.Description) %> Seems to Work!
Atømix