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?
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
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);
Method 2
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.
Method 3
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.
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0