7
votes

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

3 Answers

14
votes

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);
1
votes

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.

1
votes

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:

  1. Either create seprate page hosting different user control and when user click on the certain radio button, redirect to the respective page.

  2. 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.