How to load a user control dynamically in a page?
I have a page that contains radioButtons. Each click on a radio button loads a user control (.ascx) in the page.
What I am doing is loading all controls at the same time, but set their visibility to false. When a user clicks a radiobutton I set the visibility of the specific user control to true.
As a result I am loading all the user controls on each postback.
Is there any other possible way of doing this?
3 Answers
If you don't keep them in a List, and that list in session, you'll have lots of trouble.
Ghyath's way is the right way but you should also add them to a List.
List<Object> Usercontrols = new List<Objects>{};
Control ctrl = Page.LoadControl("UserControlPath");
Usercontrols.Add(ctrl);
Session["Usercontrols"] = Usercontrols;
On each postback, you need to reload your div with the controls in your List. Edit: I've corrected the last line.
Is there any specific reasons to hold the usercontrols in a single page?
Think about the page view state as you are loading all the controls and setting it's visibility.
I think there are two possible solutions:
Either create seprate page hosting different user control and when user click on the certain radio button, redirect to the respective page.
Load on demand i.e. when user request a user control, only then load it but removing all other loaded user controls and hence page will have only one user control at any time.