asp.net.ph

Skip Navigation Links

Using the NamingContainer Property

Web Forms Server Controls   Programming Web Forms Server Controls   Accessing Server Controls Programmatically


In certain cases, you may need to access properties or methods of a control’s naming container. Basically, the containing control can be accessed in the following ways, depending on context.

  1. access the naming container from a data-binding expression
  2. access the naming container from code

To access the naming container from a data-binding expression

During data binding, the naming container makes available a DataItem property containing the data to which controls are bound.

In the data-binding expression, use the Container keyword, which returns a reference to the container. You can then access the container’s properties or methods.

The Container keyword is used most commonly in the Eval method to get values from the naming container’s DataItem object, but can be used outside of that method as well.

The following example shows a Label control that might be in a template for a DataList, Repeater, or DataGrid control. It displays the current item number.

<asp:Label ID="myLabel" runat="server">
   <%# Container.DataItemIndex + 1 %>. <%# Eval ( "Title" ) %>
</asp:Label>

The following example is similar, but gets a value from the naming container’s DataItem object:

<asp:Label ID="myLabel" runat="server" >
   <%# DataBinder.Eval ( Container.DataItem, "Author" ) %>
</asp:Label>

NOTE: The NamingContainer property does not necessarily reference the same control as the Parent property. For example, in a Repeater control, you might have an item template containing a table that in turn contains a Label control. The parent control of the label is a table cell (for example, a HtmlTableCell object), but its naming container is the DataListItem object, because it is the DataListItem that defines the namespace for the Label control, not the table.

To access the naming container from code

Get the control’s NamingContainer property and cast it to the container’s class type, such as a GridViewRow.

 Show me 

See Also

Using the FindControl Method   Using the Controls Collection



© 2025 Reynald Nuñez and asp.net.ph. All rights reserved.

If you have any question, comment or suggestion
about this site, please send us a note