Friday, June 29, 2007

Creating ASP.Net Controls dynamically in Page_Load

I've spent two hours today trying to understand why my application works. I mean, I was glad it worked, but, based on my understanding of the ASP.Net cycle, it shouldn't have.

Long story short: in Page_Load I was instantiating and adding to the Page Controls collection some controls. To my astonishment, the postback worked! With events and everything. Even worse, even if the controls were being created every time (independent of IsPostBack) and the data was always added from the database, the postback data was overwriting it!

As far as I knew, the postback data is being loaded before the Page_Load event. And when you change something in the Page_Load, it stays changed. But things are different with dynamically generated controls. My guess is that the Page_Load method is being executed for the page, then recursively for the child controls. If a control has not yet retrieved it's postback data, it tries again.

Yet, if you try to do the same in a button event or in Page_LoadComplete, it doesn't work.

So, if you dynamically add the same controls in the Page_Load in between postbacks, the postback data will be saved and the events will fire.