简体   繁体   English

SecureChildControls()的正确用法是什么?

[英]What is the proper use of EnsureChildControls()?

Most often I use it when I am accessing a property of a composite control that depends on a child control. 当我访问依赖于子控件的复合控件的属性时,通常会使用它。 But I have also added it to OnInit of a control so I could make sure a hidden field was added correctly. 但是我也将其添加到控件的OnInit中,因此可以确保正确添加了隐藏字段。 Just a minute ago I called it in RenderControl because I was having an issue rendering a calendar extender and it fixed it. 就在一分钟前,我在RenderControl中调用了它,因为在渲染日历扩展程序时遇到了问题,并对其进行了修复。 I am starting to get a little confused on when I need to and when I don't need to call EnsureChildControls and when I should call it. 我何时需要和何时不需要调用sureChildControls以及何时应调用它变得有些困惑。 Any pointers are welcome. 欢迎任何指针。 Thanks! 谢谢!

EnsureChildControls triggers CreateChildControl if it's not already triggered before. 如果之前尚未触发CreateChildControl,则确保它会触发CreateChildControl。 This has to be done only one-time in the page life cycle. 在页面生命周期中,只能执行一次此操作。 I call it unconditionally in OnInit / Page_Init and nowhere else. 我在OnInit / Page_Init中无条件调用它,在其他任何地方都没有。 This place has the advantage that the controls are created before ASP.NET loads the ViewState. 这个地方的优点是控件是在ASP.NET加载ViewState之前创建的。 If you use the ViewState or ControlState it is necessary to create the child controls that early. 如果使用ViewState或ControlState,则必须尽早创建子控件。

EnsureChildControls method makes sure child controls are created prior to accessing them. GuaranteeChildControls方法可确保在访问子控件之前创建子控件。

Anytime you write composite controls for example, you want to build your controls inside the CreateChildControls events then call EnsureChildControls before accessing them to make sure all the controls have been created so you dont get a null reference exception. 例如,无论何时编写复合控件,您都想在CreateChildControls事件中构建控件,然后在访问它们之前先调用确保儿童控件,以确保已创建所有控件,因此不会出现null引用异常。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM