如何:在 ASP.NET 网页中按 ID 查找子控件

更新:2007 年 11 月

可以用一个方法来获取对特定控件的引用,该方法按控件 ID 搜索其命名容器。

按 ID 定位控件

  • 调用命名容器的 FindControl 方法,向该方法传递包含要使用的控件的 ID 的字符串。该方法会返回一个类型为 Control 的对象,可以将该类型强制转换为适当的类型。

    下面的代码示例演示如何定位特定的控件。该示例是 GridView 控件中某按钮的 Click 事件的处理程序。单击该按钮时,代码在当前的 GridView 项(它是 Label 控件的命名容器)中搜索名为 Label1 的控件。如果找到该控件,其文本便会显示在页面其他位置上第二个名为 LabelText 的 Label 控件中。

    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 窗体控件标识