开发者

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. Just a minute ago I called it in RenderControl because I was having an issue rendering a ca开发者_如何学编程lendar extender and it fixed it. 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. Any pointers are welcome. Thanks!


EnsureChildControls triggers CreateChildControl if it’s not already triggered before. This has to be done only one-time in the page life cycle. I call it unconditionally in OnInit / Page_Init and nowhere else. This place has the advantage that the controls are created before ASP.NET loads the ViewState. If you use the ViewState or ControlState it is necessary to create the child controls that early.


EnsureChildControls method makes sure child controls are created prior to accessing them.

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜