CesarGon
CesarGon

Reputation: 15335

Dynamically loaded ASP.NET user control fails to initialize

I am using an ASP.NET user control to encapsulate some functionality in my app. I am aware that the Page_Load handler in the control runs after the Page_Load handler in the page hosting it, so that I cannot initialize the control from the host page's Page_Load, which is annoying. I am using Page_LoadComplete on the host page to do this, and it works fine when the control is statically added to the page's HTML at design time.

However, when I try to load the control dynamically at run time, things go wrong. I successfully instantiate the control and add it to a Panel in my page. I add it to a collection so that initialization is postponed until Page_LoadComplete as in the previous case. When the code in Page_LoadComplete tries to initialize the control, however, it fails because, apparently, the control has not loaded yet. Specifically, I find that when the control's Page_Load is triggered (right after the host page's Page_Load), its local fields have not been initialized yet. For example, fields mapping the sub-controls in the user control are still null, as are other fields that I have added. You may argue that the fields I have added should be initialized by me, but the fields that map sub-controls should have been initialized before Page_Load runs, right?

Is this the expected behaviour? If so, what can I do to initialize my control properly when dynamically loading? Many thanks.

Upvotes: 0

Views: 64

Answers (1)

Steve
Steve

Reputation: 2046

event diagram

Try adding the controls in the PreInit stage so that the controls are there during the init stage and available before the processing of the postback data

Upvotes: 1

Related Questions