Lazycoder

10Feb/050

CreateChildControls before OnLoad

Interesting. I’m creating some ASP.NET controls at runtime and adding them to the page. According to page 49 of “Essential ASP.NET with Examples in C#” By Fritz Onion, which has been my insert-important-religious-book-of-your-choice for a while, the CreateChildControls method should fire before the Load event.

Now in my experience that the CreateChildControls method runs after the Load event. Ah here it is in the errata for the book.. Even though it says:

Figure 2-5: It should be clarified that the event sequence shown here occurs during a Post-back sequence. When an initial GET request is made to a page, the CreateChildControls event actually occurs after the Load event of the Page class fires.

I’m not seeing this change in the sequence in the application I’m working on. Hmmmmmm, maybe I’ll send Mr. Onion and email asking him, he can point out the obvious difference, and I can go back to banging out bad code and feeling dumb.

In any case one way you can get around this, and this is pretty important if you are dealing with dynamically created web controls and care about their ViewState, is by calling the EnsureChildControls method.

This method first checks the current value of the ChildControlsCreated property. If this value is false, the CreateChildControls method is called.

Filed under: General Leave a comment