views:

48

answers:

2

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 calendar 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!

+1  A: 

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.

Dirk
Will calling it in OnInit eliminate the need to call it in the properties if the property accesses something like TextBox1.text?
Mike
In general I say “yes”, but in detail it depends from your usage. If you call EnsureChildControls in OnInit it is secure to access the controls (through properties or otherwise) without calling it again in all subsequent stages of the pages life cycle (Load, Postback Events, Render, …) If you rely on ViewState this should be the only usage.
Dirk
A: 

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.

Andre Santos