Udostępnij za pośrednictwem


How to: Locate Child Controls by ID in an ASP.NET Web Page

You can get a reference to a specific control using a method that searches its naming container for the control's 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 code example shows how you can locate a specific control. The sample is a handler for the Click event of a button in a GridView control. When the button is clicked, the code searches for a control named Label1 in the current GridView item, which is the Label control's naming container. If the control is found, its text is displayed in a second Label control named LabelText elsewhere on the page.

    Protected Sub GridView1_ItemCommand(ByVal source As Object, _
            ByVal e As GridViewCommandEventArgs) _
            Handles GridView1.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
    
    protected void GridView1_ItemCommand(object source, 
            GridViewCommandEventArgs e)
    {
        Label l;
        l = (Label) e.Item.FindControl("Label1");
    
        if(!(l == null) ){
            LabelText.Text = l.Text;
        }
    }
    

See Also

Concepts

Web Forms Control Identification