views:

127

answers:

2

I'm trying to load a control depending on a category ID that is selected from a drop down list.

This is this code i have within a switch statement to show a usercontrol. This was the only way i knew of doing it and having reusable views. I'm open to other methods as i've read a few people saying to avoid dynamic loading?

var control =  Page.LoadControl("~/usercontrols/aCertainForm.ascx");
exampleDivArea.Controls.Add(control);

At the moment it loads fine on a button click that calls the above code but when i postback to the same form again it loses its state for the dynamic control.

Thanks for yours answers in advance, i appreciate it and hopefully soon i'll be able to help others a lot more :)

+1  A: 

The above code needs to be run early in the Page lifecycle, so that ASP.NET can then restore it's state. The server side event handler for a drop down list change event happens after all state has been restored, and so will be too late. You have to add the code to Init or somewhere like that.

(Yes, this is very ugly, and really breaks the whole ASP.NET abstraction, like many things do. Sorry :-)

spookylukey
at the moment the dropdown doesnt auto post back but the button under it changes the multiview view
Andi
OK, then that button event handler needs to have code that not only changes the multiview (for that request), but also stores some ViewState which is also read early in the Page lifecycle to set the multiview.
spookylukey
A: 

After you load the control, assign it's id. This code must run on the initial display and on postback. And make sure the id used is the same.

Here's the code I would use in Page_Load:

var control =  Page.LoadControl("~/usercontrols/aCertainForm.ascx");
control.id = "ACertainFormControl01";
exampleDivArea.Controls.Add(control);

if (IsPostBack)
{
    do stuff
}
else
{
    do stuff
}
Jeff Siver