Control.EnsureChildControls 方法


判斷伺服器控制項是否包含子控制項。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. 然後,它會取得或設定目前伺服器控制項 ControlCollection 物件中,子 TextBox Web 控制項的 Text 屬性。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. 它會建立子控制項,例如 TableTableRowTableCellLabelTextBox 控制項,這些控制項會用來呈現 GridView 產生的 HTML 資料表。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.