Disclaimer: I have read the ASP.net page life cycle, and I've also read several good articles pertaining to dynamic controls, but I must be missing something.
Background: I am currently working on a website which needs to create a lot of dynamic content based on the user's input. I understand that, in order for dynamic controls to persist and for their events to wire up correctly, I need to re-create those dynamic controls on every page post-back.
Because of the nature of my project, my code doesn't know WHAT controls to create unless it has some information about what the user selected. I'm storing the user's choices in the ViewState
, which is unavailable in Page_Init
because it has not yet loaded. Consequently, I have to wait until Page_PreLoad
or Page_Load
to read the ViewState and then re-create my dynamic controls.
The part I don't understand: When I try re-creating my controls during Page_Load
, the controls persist but the associated events don't seem to fire. For example, clicking on a LinkButton
I created does not fire the method that I wired to its Click
event, even though the button itself does persist.
A strange solution that I discovered by accident is that I can instead re-create my controls during Page_PreLoad
and then the events fire correctly.
My question (or questions, rather): Why does my problem appear to go away by re-creating my controls during Page_PreLoad
instead of Page_Load
? Is this a safe practice? I've never seen any other code that used Page_PreLoad
, which makes me wary. This solution is working for me, but are there any pitfalls I might be missing? Am I unknowingly setting myself up for failure later on?
My code, where LoadDocument()
is a method that creates controls and stuffs them into a static Panel
control:
protected void Page_PreLoad(object sender, EventArgs e)
{
if (ViewState["xmlfilename"] != null)
{
LoadDocument(ViewState["xmlfilename"].ToString());
}
}