Loading custom controls dynamically

How to load a user control dynamically on a page?
I have a page containing radioButtons. Each click on the switch loads a user control (.ascx) on the page.
What I am doing is loading all the controls at the same time, but setting their visibility to false. When the user clicks on the radio lens, I set the visibility of the specific user control to true.
As a result, I load all user controls for each postback.
Is there any other way to do this?

+7
c # user-controls
source share
3 answers

Add a div with a runat server to the page with the id "divControls", for example.

Asp allows you to dynamically load a custom .ascx control.

The code below should solve your problem.

Control ctrl = Page.LoadControl("UserControlPath"); divControls.Controls.Clear(); divControls.Controls.Add(ctrl); 
+13
source share

If you do not store them in a list, but this list is in a session, you will have many problems.

The Ghyath path is the right path, but you must also add them to the list.

 List<Object> Usercontrols = new List<Objects>{}; Control ctrl = Page.LoadControl("UserControlPath"); Usercontrols.Add(ctrl); Session["Usercontrols"] = Usercontrols; 

With every callback, you need to reload the div using the controls in your list. Edit: I fixed the last line.

+1
source share

Are there any specific reasons to keep user controls on the same page?

Think about the pageview state when you download all the controls and set its visibility.

I think there are two possible solutions:

  • Or create a separate page that hosts a different user control, and when the user clicks on a specific switch, redirect to the corresponding page.

  • Download on demand, i.e. when a user requests a user control, loads it, but deletes all other loaded user controls, and therefore the page will have only one user control at any time.

0
source share

All Articles