简体   繁体   中英

Loading user controls dynamically

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?

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

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM