Control.FindControl 方法

定义

在当前的命名容器中搜索指定的服务器控件。

重载

FindControl(String)

在当前的命名容器中搜索带指定 id 参数的服务器控件。

FindControl(String, Int32)

使用指定的 idpathOffset 参数(该参数有助于搜索)中指定的整数在当前命名容器中搜索服务器控件。 不应重写此版本的 FindControl 方法。

FindControl(String)

在当前的命名容器中搜索带指定 id 参数的服务器控件。

public:
 virtual System::Web::UI::Control ^ FindControl(System::String ^ id);
public virtual System.Web.UI.Control FindControl (string id);
abstract member FindControl : string -> System.Web.UI.Control
override this.FindControl : string -> System.Web.UI.Control
Public Overridable Function FindControl (id As String) As Control

参数

id
String

要查找的控件的标识符。

返回

指定的控件,如果指定的控件不存在则为 null

示例

以下示例定义 Button1_Click 事件处理程序。 调用时,此处理程序使用 FindControl 方法在包含页上查找 属性为 IDTextBox2 控件。 如果找到控件,则使用 Parent 属性确定其父控件,并将父控件的 ID 写入页面。 如果未 TextBox2 找到 ,则会将“找不到控件”写入页面。

重要

此示例具有一个接受用户输入的文本框,这是一个潜在的安全威胁。 默认情况下,ASP.NET 网页验证用户输入是否不包含脚本或 HTML 元素。 有关详细信息,请参阅脚本侵入概述

private void Button1_Click(object sender, EventArgs MyEventArgs)
{
      // Find control on page.
      Control myControl1 = FindControl("TextBox2");
      if(myControl1!=null)
      {
         // Get control's parent.
         Control myControl2 = myControl1.Parent;
         Response.Write("Parent of the text box is : " + myControl2.ID);
      }
      else
      {
         Response.Write("Control not found");
      }
}

Private Sub Button1_Click(sender As Object, MyEventArgs As EventArgs)
' Find control on page.
Dim myControl1 As Control = FindControl("TextBox2")
If (Not myControl1 Is Nothing)
   ' Get control's parent.
   Dim myControl2 As Control = myControl1.Parent
   Response.Write("Parent of the text box is : " & myControl2.ID)
Else
   Response.Write("Control not found.....")
End If
End Sub

注解

使用 FindControl 从代码隐藏页中的函数访问控件,用于访问另一个容器中的控件,或者在调用方无法直接访问目标控件的其他情况下访问控件。 仅当控件直接包含在指定的容器中时,此方法才会找到控件;也就是说, 方法不会在控件内的控件层次结构中进行搜索。 有关如何在不知道控件直接容器时查找控件的信息,请参阅 如何:按 ID 访问服务器控件

另请参阅

适用于

.NET Framework 4.8.1 和其他版本
产品 版本
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1

FindControl(String, Int32)

使用指定的 idpathOffset 参数(该参数有助于搜索)中指定的整数在当前命名容器中搜索服务器控件。 不应重写此版本的 FindControl 方法。

protected:
 virtual System::Web::UI::Control ^ FindControl(System::String ^ id, int pathOffset);
protected virtual System.Web.UI.Control FindControl (string id, int pathOffset);
abstract member FindControl : string * int -> System.Web.UI.Control
override this.FindControl : string * int -> System.Web.UI.Control
Protected Overridable Function FindControl (id As String, pathOffset As Integer) As Control

参数

id
String

要查找的控件的标识符。

pathOffset
Int32

页面控件层次结构上到达命名容器所需的控件的数量。

返回

指定的控件,如果指定的控件不存在则为 null

适用于

.NET Framework 4.8.1 和其他版本
产品 版本
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1