Reputation: 14555
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?
Upvotes: 7
Views: 29598
Reputation: 17556
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.
Upvotes: 1
Reputation: 5638
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.
Upvotes: 1
Reputation: 7632
Add a div with runat server on the page with an id "divControls" for example.
Asp allow you to load a user control ".ascx" dynamically.
The below code should solve your problem.
Control ctrl = Page.LoadControl("UserControlPath");
divControls.Controls.Clear();
divControls.Controls.Add(ctrl);
Upvotes: 15