tags:

views:

39

answers:

1

I got this working by trial and error but would really appreciate an explanation.

Summary: I am dynamically loading usercontrols from the host page.

Host Page .aspx

OnInit does a LoadControl and loads the control

User control .ascx

On Page_Load
-> First time load
    --> I set a value to a hidden input type variable
    --> I set a value to a ViewState object (using ViewState["test"] = "test")
-> Subsequent post backs
    --> Hidden var still persists
    --> ViewState is NULL !! (Why?)

If i move the code from Page_Load to Oninit:
-> Subsequent post backs
   --> Both hidden var and Viewstate is NULL!

Why??

+1  A: 

Viewstate is loaded after the Init phase, so of course it's null in your 2nd scenario.

This is why you need to load your controls there: because if you wait until after viewstate is loaded then the state wouldn't be restored for the controls- it's already passed that phase.

Joel Coehoorn
I could swear that the first time I read your question you were using the Init event for the first two items rather than the Load event. :(
Joel Coehoorn
Oh well, at least this still explains why your hidden input is null in the last scenario: it's state wasn't restored yet.
Joel Coehoorn