Thursday, July 17, 2008

Back to Basics - Page_Load & OnPreRender events with nested Web Controls

While working on some refactorings in my recent project I came across a piece of what I would like to call ‘ignorant code’*.

I have tried to get the gist of the scenario with the below diagram :


scenario


Its a pretty basic scenario where we have multiple web controls clubbed together in a single control. (Although I not a huge fan of nested web controls)

What’s important to consider here is the use of Page_Load and OnPreRender events in the Parent and Child web controls.

Probably we all know that Page_Load always occurs before the OnPreRender but the OnPreRender only occurs if the ‘Visible’ property of the web control is set to true.

So in the above scenario although the controls were made visible according to the page, the Page_Load event of all the 7 sub web controls was called everytime. The solution to this is to simply move the hefty code from Page_Load to the OnPreRender event. As the rendering would only occur if the control is visible it would only execute the hefty code on the relevant pages.

*ignorant Code : No code is crap code or bad code its just that we do not know a better way to do it at that point of time

No comments:

AddIn