4

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?

Xerion
  • 3,141
  • 5
  • 30
  • 46

4 Answers4

5

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.

Muad'Dib
  • 28,542
  • 5
  • 55
  • 68
3

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.

rahul
  • 184,426
  • 49
  • 232
  • 263
0

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()?

JustLoren
  • 3,224
  • 3
  • 27
  • 34
  • No, I am saying using CreateChildControls is more performant due to the potential to avoid unnecessary work. However, sometimes one needs to wait for, say base.OnLoad, because it gets some data that will determine how you should create the children. In this case, there's no way to delay child creation until after OnLoad since you dont know when EnsureChildControls will be called. It works if I just create everything in OnLoad... – Xerion Oct 01 '09 at 23:46
  • @Xerion: Fair enough. I'm not sure why your CreateChildControls can't fetch the data, but I'm sure there's some design reason to. – JustLoren Oct 02 '09 at 12:53
  • What a silly "optimization" if that's the best argument. Who cares if the request takes 150ms and not 149.5ms if it results in a 400/500 *which should be rare*? –  Aug 06 '12 at 02:19
0

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.

Daniel
  • 1,783
  • 1
  • 14
  • 15