Wednesday, 07 March 2007

Every ASP.NET developer knows (or at least should know) about the Life Cycle. Page has it's Life Cycle, controls have theirs Life Cycle (more or less the same as the one of the Page). There is a good article on MSDN regarding the Page Life Cycle. From it, you will learn that at any given moment, the Page and all controls are in the same "phase" of the Life Cycle, be it Init, Load, PreRender or Unload.

The interesting part about the Life Cycle is when it comes to dynamically added controls. The controls you add in code using Controls.Add call. Since controls also have the Init, Load and PreRender and Unload phases, what happens when we add a new control during a PreRender phase? As stated above, Page and all controls are always in the same phase. So what happens?

The same article explains this phenomenon and calls it "Catch-up". What it basically means is that at the time of adding a control to a Controls collection, the new control "walks" through all it's phases until it "catches-up" with the current phase of it's parent control (i.e. Page).

In order to better understand this, you can use the following example. On your page override an OnPreRender method and add a following code:

protected override void OnPreRender(EventArgs e)
    Button b = new Button();
    b.Load += new EventHandler(b_Load);
    b.Init += new EventHandler(b_Init);
    b.PreRender += new EventHandler(b_PreRender);
    b.Unload += new EventHandler(b_Unload);

You will also need to create the event handler methods. As the next step, put a break point on each of those handler methods and run the debugger to see what happens. You will notice that when control is added to a collection of Controls, it's events are fired immediately to catch up with the phase of its parent.

kick it on