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 网页验证用户输入是否不包含脚本或 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. 它创建子控件如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.