How to find child control’s position in a parent repeater

If you have repeater inside a repeater, in some situation you may need to find position of control( that’s inside child repeater) in parent repeater.  Let’s take an example.  Here is what I have.

<asp:Repeater runat="server" ID="rptParent"  >
  <ItemTemplate>
    <uc:control runat="server" id="ucParent"></uc:control>

       <asp:Repeater runat="server" ID="rptChild">
          <ItemTemplate>
             <uc:control runat="server" id="ucChild"></uc:control>
          </ItemTemplate>
       </asp:Repeater>

  </ItemTemplate>
</asp:Repeater>
As you can see in sample code above, I have child repeater “rptChild” inside a parent repeater “rptParent”. Same user control is inside child and parent repeater control. Let’s say “ucChild” user control triggers ItemCommand event of repeater “rptChild” and you want to find instance of user control “ucParent” of parent repeater and call its method/event.  RepeaterCommandEventArgs object will give you an repeaterItem where “ucChild” is residing using e.Item.  There is a “NamingContainer” property of control that inherits from System.Web.UI.Control.
  • e.Item will give “RepeaterItem” object and that is inherited from System.Web.UI.Control. “NamingContainer” property will give you a control object where it’s residing in.  That means e.Item.NamingContainer will give you child repeater object “rptChild” because repeaterItem is residing inside a “rptChild”.
  • e.Item.NamingContainer.NamingContainer will give you a repeaterItem object of “rptParent” because child repeater (“rptChild”) is residing inside a repater item of parent repeater. Now you can use FindControl method to find “ucParent” because “ucParent” control is residing inside a RepeaterItem of parent repeater.

e.Item.NamingContainer.NamingContainer.FindControl(“ucParent”)

And if you want to find the position of “ucChild” control inside a parent repeater control, you can use e.Item.Item.NamingContainer.NamingContainer and type cast it to RepeaterItem object and user ItemIndex propety.

CType(e.Item.Item.NamingContainer.NamingContainer,RepeaterItem).ItemIndex

Hope this helps.  If this post really helps you, please click the Google +1 button to show it really helps you save your time.
Posted in Microsoft Technology Tagged with: ,
2 comments on “How to find child control’s position in a parent repeater
  1. betonmma says:

    I see you put a lot of work in your site Keep writing!

  2. Anonymous says:

    thanks
    very nice article…perfect.

Ads