views:

659

answers:

2

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?

A: 

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).

Colin
Yes I'm sure... :-(
spa
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.
spa
+4  A: 

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.

Robba
That's a good answer.
spa