Xerion
Xerion

Reputation: 3281

When "must" I use asp.net CreateChildControls()?

While it seems that the "right" way to make a server control is to construct all child controls inside CreateChildControls call. But since it's difficult to know when it will be called (which is the whole point as a perf optimzation), I see most of our devs construct in OnInit, or OnLoad. And this works 99% of the case.

Are there cases where we have to use CreateChildControls?

Upvotes: 4

Views: 8564

Answers (4)

Muad'Dib
Muad'Dib

Reputation: 29256

You should ALWAYS construct your child controls in CreateChildControls. This is the proper time in the Lifecycle to initialize and add them to the control tree. One of the reasons for this is that many times the method EnsureChildContols is called, which then calls CreateChildControls if necessary. Best Practice, just do it.

Upvotes: 6

Daniel
Daniel

Reputation: 1793

You will get away with creating your controls in Init or Load until you write a control that needs to recreate the controls.

I find it is always best to create the controls in CreateChildControls and then use EnsureChildControls to control ensure they are created when you need them. This allows you the ability to tear down the controls by setting ChildControlsCreated to false and have them recreated again when needed.

Upvotes: 0

JustLoren
JustLoren

Reputation: 3234

Performance-wise, waiting to create a child control will save your server some unnecessary CPU time. For example, if an exception is raised or the thread is aborted prior to CreateChildControls() being called, the clock cycles necessary to create those controls are saved.

What's your reasoning for saying that creating controls in OnInit is more performant than during CreateChildControls()?

Upvotes: 0

rahul
rahul

Reputation: 187100

Read Control Execution Lifecycle

The CreateChildControls method is called whenever the ASP.NET page framework needs to create the controls tree and this method call is not limited to a specific phase in a control's lifecycle. For example, CreateChildControls can be invoked when loading a page, during data binding, or during rendering.

Upvotes: 3

Related Questions