adding user controls at runtime

S

Sam Kuehn

There has been a lot of articles on how to load user controls at runtime in the Init() method.
UserControl myControl = (UserControl)LoadControl(stringControl);
I add the control in the Init() method so that the viewstate to works properly. What if I want to let the user select what control to display? For instance say I have a drop down list of user controls and want to load the control the user has selected? When the user selects a control the form will auto postback. But at the point Init() method is fired the users selection in the on change event handler for the drop down list has not been set.
So here is what is happening (I think):
Init()
{
//this method adds control to form
AddUserControl(SessionManager.Instance.SomeValue);
}
ddl_IndexChanged()
{
//Add to session so that is available tot he Init() method
SessionManager.Instance.SomeValue = int.Parse(e.Node.DataKey.ToString());
}
So when a user changes a drop down list Init() is called and THEN (the problem) the session variable that tells the AddUserControl() method what control to load is set. So if I were to reload the page without changing the drop down the second time the page would display correctly. Basically the control loaded is always one postback "behind" what the user has selected. Is there any solutions to this problem? I have a lot of instances where it would be nice to load a user control on the fly and I might not know at design time what control I want to load. It my be dictated by user input. I am sure there is a best practices way to accomplish this. It seems like a problem that many people would have run into.

Many thanks in advance!

Posted by JetBrains Omea Reader 341.19
 
G

Guest

Can you not put this code in the page_load event? I don't remember having any
problems with my viewstate when doing this. Although I don't provide the
ability to allow users to load controls but I would imagine this would work
fine.

Ian
 
S

Sam Kuehn

Hello ENIZIN,
I could possibly add it to the page_load event but I will still have the same problem. Page_load is called before ddl_Index changed method. It is like I have to reload the page after the ddl_Index tell the session vaiable (or whatever) what control to load. Bottom line is that both Init and page_load are called before the event handler for the dropdown list, button or what ever. I guess a work around would be a Response.Redirect back to itself. Problem with that is you loose viewstate info.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,055
Latest member
SlimSparkKetoACVReview

Latest Threads

Top