User Controls, postbacks and ViewState
Posted on 2010-08-20
I am dynamically loading User Controls onto a page based on a specific URL parameter (foobar.aspx?pageid=3 for example) and adding the User Controls to a PlaceHolder control on the page. In the PageLoad event in if not page.ispostback then I add the URL parameter to the ViewState i.e. ViewState("id")=3.
I understand that in order for the ViewState to get loaded back into the dynamically added User Controls, the User Controls need to be dynamically added again.
If my understanding is correct, this re-adding of User Controls has to happen before the Page Load event. If that is the case, how do I get the ViewState("id") value if the re-adding happens before the PageLoad event, for instance in the Page_Init. I don't think the ViewState is available from this event.
My workaround is to just request the URL parameter in the Page_Init again. i.e. I do GetUserControls(Request.Querystring("id")) as opposed to GetUserControls(ViewState("id")).
Is there a better way? Is this a valid way of doing this? Any help is greatly appreciated.