다음을 통해 공유


방법: ASP.NET 웹 페이지에서 ID로 자식 컨트롤 찾기

업데이트: 2007년 11월

컨트롤 ID로 명명 컨테이너를 검색하는 메서드를 사용하여 특정 컨트롤에 대한 참조를 가져올 수 있습니다.

ID로 컨트롤을 찾으려면

  • 명명 컨테이너의 FindControl 메서드를 호출하고 사용할 컨트롤의 ID가 포함된 문자열을 메서드에 전달합니다. 이 메서드는 적절한 형식으로 캐스팅할 수 있는 Control 형식의 개체를 반환합니다.

    다음 코드 예제에서는 특정 컨트롤을 찾는 방법을 보여 줍니다. 이 샘플은 GridView 컨트롤에 있는 단추의 Click 이벤트에 대한 처리기입니다. 단추를 클릭하면 코드를 통해 Label 컨트롤의 명명 컨테이너인 현재 GridView 항목에서 Label1 컨트롤이 검색됩니다. 컨트롤을 찾으면 페이지의 두 번째 Label 컨트롤(LabelText)에 이 컨트롤의 텍스트가 표시됩니다.

    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;
        }
    }
    

참고 항목

개념

Web Forms 컨트롤 식별