Control.FindControl 方法
定義
重要
部分資訊涉及發行前產品,在發行之前可能會有大幅修改。 Microsoft 對此處提供的資訊,不做任何明確或隱含的瑕疵擔保。
搜尋目前命名容器中指定的伺服器控制項。
多載
| 名稱 | Description |
|---|---|
| FindControl(String) |
在目前命名容器中搜尋具有指定 |
| FindControl(String, Int32) |
搜尋目前的命名容器,使用指定的 |
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 方法在包含頁面上尋找具有屬性 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)
搜尋目前的命名容器,使用指定的 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
頁面控制階層中需要的控制項數量,才能到達命名容器。
傳回
指定的控制點,或 null 是該指定的控制不存在。