Control.EnsureChildControls Control.EnsureChildControls Control.EnsureChildControls Control.EnsureChildControls Method


判斷伺服器控制項是否包含子控制項。Determines whether the server control contains child controls. 如果不包含,則建立子控制項。If it does not, it creates child controls.

 virtual void EnsureChildControls();
protected virtual void EnsureChildControls ();
abstract member EnsureChildControls : unit -> unit
override this.EnsureChildControls : unit -> unit
Protected Overridable Sub EnsureChildControls ()


下列範例會使用EnsureChildControls確保目前的伺服器控制項的子控制項的方法。The following example uses the EnsureChildControls method to ensure that the current server control has child controls. 然後取得或設定Text屬性的子TextBoxWeb 控制項中目前伺服器控制項的ControlCollection物件。It then gets or sets a Text property for a child TextBox Web control in the current server control's ControlCollection object.


這個範例有一個可接受使用者輸入的文字方塊,這可能會造成安全性威脅。This example has a text box that accepts user input, which is a potential security threat. 根據預設,ASP.NET Web 網頁會驗證使用者輸入未包含指令碼或 HTML 項目。By default, ASP.NET Web pages validate that user input does not include script or HTML elements. 如需詳細資訊,請參閱 Script Exploits Overview (指令碼攻擊概觀)。For more information, see Script Exploits Overview.

// Ensure the current control has children,
// then get or set the Text property.
 public int Value {
    get {
        return Int32.Parse(((TextBox)Controls[1]).Text);
    set {
        ((TextBox)Controls[1]).Text = value.ToString();

' Ensure the current control has children,
' then get or set the Text property.

Public Property Value() As Integer
      Return Int32.Parse(CType(Controls(1), TextBox).Text)
   End Get
      CType(Controls(1), TextBox).Text = value.ToString()
   End Set
End Property


這個方法會先檢查目前的值ChildControlsCreated屬性。This method first checks the current value of the ChildControlsCreated property. 如果這個值是false,則CreateChildControls呼叫方法。If this value is false, the CreateChildControls method is called.

EnsureChildControls方法通常會在複合控制項,也就是使用部分的子控制項的控制項或所有其功能。The EnsureChildControls method is typically used in composite controls, which are controls that use child controls for some or all their functionality. EnsureChildControls會呼叫方法,若要確定已建立的子控制項,並已準備好處理輸入,來執行資料繫結,或執行其他工作。The EnsureChildControls method is called in order to make sure that child controls have been created and are ready to process input, to perform data binding, or to perform other tasks.

GridView控制項是複合控制項的範例。The GridView control is an example of a composite control. 它會建立子控制項這類TableTableRowTableCellLabel,並TextBox控制項,用來呈現 HTML 資料表,其中GridView產生。It creates child controls such as Table, TableRow, TableCell, Label, and TextBox controls, which are used to render the HTML table that the GridView generates.

在大部分情況下,自訂伺服器控制項開發人員就不必覆寫這個方法。In most cases, custom server control developers do not have to override this method. 如果您覆寫這個方法,則會使用預設的行為類似的方式。If you do override this method, use it in a way similar to the default behavior.