Why does OnLoad / CreateChildControls order change at postback?
Asked Answered
K

2

10

The web part lifecycle is described like this:

On Page Load

  1. Constructor
  2. OnInit
  3. OnLoad
  4. ConnectionConsumer method is called if web part is connectable
  5. CreateChildControls ...

On 1st Postback (PostBack click handler sets ViewState via public Property)

  1. Constructor
  2. OnInit
  3. CreateChildControls
  4. OnLoad
  5. PostBack click handling ...

On 2nd Postback (PostBack click handler sets ViewState via public Property)

  1. Constructor
  2. OnInit
  3. LoadViewState
  4. CreateChildControls
  5. OnLoad ...

As you can see the OnLoad and CreateChildControls change their order. This introduces some difficulties in my code as I need to gather various data which I used to do in the OnLoad element.

Is there any reason why the order is changed in the post back phase?

Keef answered 30/10, 2009 at 7:20 Comment(0)
C
15

CreateChildControls is called whenever the framework (or yourself) calls the EnsureChildControls method. This method should be called whenever you need the child controls to be there.

In the case of the framework it wants to set the posted values between the OnInit and the OnLoad (so that you may access the values during OnLoad). Because it needs the controls to do this, it'll call EnsureChildControls for you.

If there is no postback, there is also no need to set the values and thus the call to EnsureChildControls will wait until such a time the framework does need the controls. This happens to be between the OnLoad and the OnPreRender.

Clandestine answered 8/12, 2009 at 22:56 Comment(0)
S
-4

That shouldn't happen, are you absolutely sure? Are there no other threads running that might make it seem as though the order has changed?

This is after all just ASP.NET, a program executed by a computer (meaning it should always do things the same, unlike a person).

Skeptical answered 30/10, 2009 at 8:13 Comment(1)
This isn't anything which I came up myself. It is described in various blog post (see the link in the question). I verified it with the debugger.Keef

© 2022 - 2024 — McMap. All rights reserved.