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 网页验证用户输入是否不包含脚本或 HTML 元素。By default, ASP.NET Web pages validate that user input does not include script or HTML elements. 有关详细信息,请参阅脚本侵入概述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.