Export (0) Print
Expand All

Referencing Controls in Web Forms Pages

Visual Studio .NET 2003

When you are working with controls in templates, you cannot always directly reference the controls in code. For example, if you add a Label control to a DataList control and name it "Label1," you cannot get or set its properties at run time by simply referring to Label1 in code. The page class does not contain an instance of the control that you can use directly, because there are typically multiple instances of the control. For more information, see Web Forms Control Identification.

Similarly, there are times when you are working with a control and need access to properties or methods of its naming container.

The sections below describe various ways in which you can get access to controls when you are working with naming containers and child controls.

Locating a Child Control by ID

You can get a reference to a specific control using a method that searches its naming container by its assigned ID.

To locate a control by ID

  • Call the FindControl method of the naming container, passing it a string containing the ID of the control you want to use. The method returns an object of type Control that you can cast to the appropriate type.

    The following example shows how you can locate a specific control. The sample is a handler for the Click event of a button in a DataGrid control. When the button is clicked, the code searches for a label named Label1 in the current DataGrid item (which is the Label control's naming container). If the label is found, its text is displayed in a second label (LabelText) elsewhere on the page.

    ' Visual Basic
    Private Sub DataGrid1_ItemCommand(ByVal source As Object, _
       ByVal e As System.Web.UI.WebControls.DataGridCommandEventArgs) _
       Handles DataGrid1.ItemCommand
       Dim l As Label
       l = CType(e.Item.FindControl("Label1"), Label)
       If (Not l Is Nothing) Then
          LabelText.Text = l.Text
       End If
    End Sub
    
    // C#
    private void DataGrid1_ItemCommand(object source, 
       System.Web.UI.WebControls.DataGridCommandEventArgs e)
    {
       Label l;
       l = (Label) e.Item.FindControl("Label1");
       
       if(!(l == null) ){
          LabelText.Text = l.Text;
       }
    }
    

Accessing Members of the Naming Container

At times, you need to access properties or methods of a control's naming container. For example, during data binding, the container control makes available a DataItem property containing the data to which controls are bound. You can access the containing control in different ways, depending on context.

In Declarative Data-Binding Expressions

In data-binding expressions, you can access the container control using the special keyword Container. (For information on these expressions, see Data-Binding Expressions for Web Forms Pages.)

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. You can then access the container's properties or methods.

    This keyword is used most commonly in the DataBinder.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=Label1 runat="server" 
       Text='<%# Container.ItemIndex + 1  %>'>
    </asp:Label>
    

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

    <asp:Label id=Label1 runat="server" 
       Text='<%# Container.DataItem("title") %>'>
    </asp:Label>
    

In Code

In the code for a page, you can access a control's naming container by getting its NamingContainer property.

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 DataGridItem.

    For an example of using the NamingContainer property to get information about an individual control's naming container, see the section "Selecting Multiple Items Using a Check Box (Hotmail Model)" in the article Top Questions about the DataGrid Web Server Control.

Locating a Control by Walking the Controls Collection

Every container control on the page, and the page itself, has a Controls collection that you can use to get to individual controls.

To locate controls in the Controls collection

  • Loop through the Controls collection of the container control. The collection is of type ControlCollection, and returns objects of type Control.

    The following example illustrates how to walk the Controls collection. The example assumes a Web Forms page with at least one Textbox control on it, a Label control, and a button. The code gets all the child controls of the Page object. Because this would produce only a few high-level child controls, including the HtmlForm object, the code also walks the Controls collection of each individual child control. The code looks for text boxes by comparing the type of each control. When it finds a text box, it gets that control's value and concatenates it into a string that is displayed at the end in a Label control.

    This example finds only the controls contained in the Page object and the controls that are direct children of the page. It does not find text boxes that are children of a control that is in turn a child of the page. For example, if you dragged a Panel control on the designer, the Panel control would be a child of the HtmlForm control contained by the Page, and it would be found in this example. However, if you then dragged a TextBox control onto the Panel control, the TextBox control text would not be displayed by the example, because it is not a child of the page or of a control that is a child of the page. A more practical application of walking the controls this way would be to create a recursive method that can be called to walk the Controls collection of each control as it is encountered. However, for clarity, the example below is not created as a recursive function.

    ' Visual Basic
    Private Sub Button1_Click(ByVal sender As System.Object, _
       ByVal e As System.EventArgs) Handles Button1.Click
       Dim allTextBoxValues As String = ""
       Dim c As Control
       Dim childc As Control
       For Each c In Page.Controls
          For Each childc In c.Controls
             If TypeOf childc Is TextBox Then
                allTextBoxValues &= CType(childc, TextBox).Text & ","
             End If
          Next
       Next
       If allTextBoxValues <> "" Then
          Label1.Text = allTextBoxValues
       End If
    End Sub
    
    // C#
    private void Button1_Click(object sender, System.EventArgs e)
    {
       string allTextBoxValues = "";
       foreach (Control c in Page.Controls)
       {
          foreach (Control childc in c.Controls)
          {
             if (childc is TextBox)
             {    
                allTextBoxValues += ((TextBox)childc).Text + ",";
             }
          }
       }
       if(allTextBoxValues != "")
       {
          Label1.Text = allTextBoxValues;
       }
    }
    

See Also

Web Forms Control Identification

Show:
© 2014 Microsoft