How to: Access Members of a Control's Naming Container
At times, you need to access properties or methods of a control's naming container. You can access the containing control in different ways, depending on context.
To access the naming container from a data-binding expression
-
In the data-binding expression, use the Container keyword, which returns a reference to the container.
The following example shows a Label control that is inside of the ItemTemplate of a GridView control. It displays the current item number followed by the Title data item of the naming container.
To access the naming container from code
-
Get the control's NamingContainer property and cast it to the container's class type.
Note
The NamingContainer property might not reference the same control as the Parent property. For example, in a Repeater control, an item template might contain a table that in turn contains a Label control. In that case, the parent control of the Label control is a table cell (for example, a HtmlTableCell object), but its naming container is the DataListItem object. This is because the DataListItem defines the namespace for the Label control, not the table.
The following example shows 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 by using the FindControl method, and then determines the NamingContainer object for that control. The code 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. (The WalkContainers method will also add the type of the control at the lowest level, which is not a naming container.)