December 2006 - Posts

Accessing Parent DataItem of a Child DataItem

We've all iterated through some kind of repeater (datalist, datagrid, an ACTUAL repeater) and used the DataBinder to display a property of the object bound to the current DataItem without wasting time writing an ItemDataBound event handler:

<asp:Repeater>
   <ItemTemplate>
      <%#DataBinder.Eval(Container.DataItem, "PropertyName")%>
   </ItemTemplate>
</asp:Repeater>

But have you ever been iterating through a Repeater WITHIN a Repeater and wondered: "gee, how do I access the outer DataItem for display within the inner DataItem's template without writing a complicated ItemDataBound event handler?"  I.e.

<asp:Repeater ID="_outerRepeater">
   <ItemTemplate>
      <%#DataBinder.Eval(Container.DataItem, "PropertyName")%>
      <asp:Repeater ID="_innerRepeater">
         <ItemTemplate>
            [Outer Repeater DataItem]
            <%#DataBinder.Eval(Container.DataItem, "PropertyName")%>
         </ItemTemplate>
      </asp:Repeater>
   </ItemTemplate>
</asp:Repeater>

Well, I wondered just that the other day.  I asked around to see if there was a shortcut anybody around inetium knew, to no avail.  Seems everyone thought it should be easy, but they had never thought to attempt it before.  Googling was a bit challenging for this task (what would you put in the search box?), so I begain tinkering in code, using asp.net 2.0 in Visual Studio 2005 for increased intellisense and figured out this solution:

<asp:Repeater ID="_outerRepeater">
   <ItemTemplate>
      <%#DataBinder.Eval(Container.DataItem, "PropertyName")%>
      <asp:Repeater ID="_innerRepeater">
         <ItemTemplate>
<%#((System.Web.UI.WebControls.RepeaterItem)Container.Parent.Parent).DataItem%>
            <%#DataBinder.Eval(Container.DataItem, "PropertyName")%>
         </ItemTemplate>
      </asp:Repeater>
   </ItemTemplate>
</asp:Repeater>

The container is what holds the DataItem (in an event handlers, that'd be e.Item I'd guess) and it's parent is the inner repeater.  So you'll need the inner repeater's parent, the outer repeater's DataItem.  Seems to call the ToString() method of it, so it's limited, but that's exactly what I wanted (I was binding the outer repeater do directories and the inner repeater to files inside of that directory, so the point was to get a link to [Directory Name]/[File Name].

Posted by vbullinger | 4 comment(s)