Using the NamingContainer Property to Determine a Control's Naming Container

You can walk up the control tree on a page by means of the NamingContainer property. In contrast to the Container keyword, which is available only in inline code (that is, in a declarative <%#   %> expression), the NamingContainer property is available in code to any instance of that class or of a derived class.

The following code example illustrates how to walk the control tree of an ASP.NET Web page. The button's ChangeBtn_Click method handler searches for a control named Message in the first item of a Repeater control using the FindControl method, and then determines the NamingContainer object for that control. It then determines the naming container for the control returned by the first call to the NamingContainer property, and so on up the control tree until it finds a control that has no naming container. (Note that the WalkContainers method will also add the type of the control at the lowest level, which is not itself a naming container.)

<html xmlns="" >

<head id="head1" runat="server">
    <title>NamingContainer Example</title>

<script language="c#" runat="server">

    ArrayList list;

    private void Page_Load(object sender, EventArgs e)
        list = new ArrayList();
        MyRepeater.DataSource = list;

    private void ChangeBtn_Click(object sender, EventArgs e)
        Control x = MyRepeater.Items[0].FindControl("Message");
        if (x != null) list = WalkContainers(x);
        MyRepeater.DataSource = list;

    private ArrayList WalkContainers(Control ctl)
        ArrayList ret = new ArrayList();
        Control parent = ctl.NamingContainer;
        if (parent != null)
            ArrayList sublist = WalkContainers(parent);
            for (int j = 0; j < sublist.Count; j++) ret.Add(sublist[j]);
        return ret;

<form id="repeaterform" runat="server">
  <h3>Using the NamingContainer Property to Determine a 
      Control's Naming Container
  <table id="mytable" width="80%">
      <asp:repeater id="MyRepeater" runat="server">
          <td align="center" style="width:100%;">
           <span id="message" runat="server">
      <td align="center" style="width:100%;">
      <input id="changebtn" 
             runat="server" />

See Also