Control.FindControl 方法

定義

在目前的命名容器搜尋指定的伺服器控制項。

多載

FindControl(String)

在目前命名容器搜尋具有指定 id 參數的伺服器控制項。

FindControl(String, Int32)

使用指定的 id 和有助於搜尋之 pathOffset 參數中所指定的整數,在目前的命名容器中搜尋伺服器控制項。 您不應該覆寫這個版本的 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 使用 方法,在包含頁面上尋找 具有 IDTextBox2 屬性的控制項。 如果找到控制項,則會使用 Parent 屬性來判斷其父控制項,而父控制項的 ID 會寫入頁面。 如果 TextBox2 找不到 ,則會將「找不到控制項」寫入頁面。

重要

這個範例有一個可接受使用者輸入的文字方塊,這可能會造成安全性威脅。 根據預設,ASP.NET Web 網頁會驗證使用者輸入未包含指令碼或 HTML 項目。 如需詳細資訊,請參閱 Script Exploits Overview (指令碼攻擊概觀)。

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 從程式碼後置頁面中的函式存取控制項、存取位於另一個容器內的控制項,或在呼叫端無法直接存取目標控制項的其他情況下。 只有在控制項直接由指定的容器包含時,這個方法才會找到控制項;也就是說,方法不會在控制項內的控制項階層中搜尋。 如需如何在您不知道其立即容器時尋找控制項的相關資訊,請參閱 如何:依識別碼存取伺服器控制項

另請參閱

適用於

FindControl(String, Int32)

使用指定的 id 和有助於搜尋之 pathOffset 參數中所指定的整數,在目前的命名容器中搜尋伺服器控制項。 您不應該覆寫這個版本的 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

適用於