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

要查找的控件的标识符。

返回

Control

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

示例

以下示例定义 Button1_Click 事件处理程序。 调用时,此处理程序使用 FindControl 该方法查找包含 ID 页面上属性的 TextBox2 控件。 如果找到控件,则使用 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 访问服务器控件”。

另请参阅

适用于

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

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

返回

Control

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

适用于