ASP.NET dynamically changes the source of user management

Scenario

I have an ASP.Net web project that uses the main page. This main page contains a menu as a user control. Sometimes I want to dynamically change this to use a different type of user control.

Current code for registering a user control

<%@ Register TagPrefix="chase" TagName="topMenu" Src="~/UserControls/TopMenu.ascx" %> 

Inside body tags

  <div id="menuRow"> <chase:topMenu runat="server" /> </div> 

Question

In any case, can I change the "SRC" attribute in the register code dynamically to use a different user control ?!

Help with thanks

EDIT:

Tried this code but get "Invalid Cast Exception"

 TopMenu uh3 = (TopMenu)this.LoadControl("~/UserControls/TopMenu.ascx"); menuRow.Controls.Add(uh3); 

'Unable to pass object of type' ASP.usercontrols_topmenu_ascx 'to enter' SwintonTaxiWeb.UserControls.TopMenu '.

+4
source share
6 answers

What if you add your user control at runtime what you need.

 UserControls_header3 uh3 = (UserControls_header3)this.LoadControl(header3); phHeaderControls.Controls.Add(uh3); 
+1
source

Have you tried to use two user controls registered on the page and hide / disable accordingly.

0
source

What causes dynamic changes?

You can do this in server side code quite easily.

On the .aspx page you can:

 <asp:Panel id="menuRow" runat="server"> </asp:Panel> 

I use Panel here because it gives us a nice container for controls and displays a <div> around them.

Then in your code behind, you will have something like:

 // Determine correct user control to load string pathToUserControl = DetermineTopMenu(); // Load the user control - calling LoadControl forces the correct lifcycle events // to fire, and ensures the control is created properly. var topMenu = LoadControl(pathToUserControl); // Add the control to the menuRow panels control collection. menuRow.Controls.Add(topMenu); 

I suggested that you have a way to determine which user control you want to display, and that you named it in such a way as to generate the path to the user control quite difficult. I hid this logic in a call to the DetermineTopMenu method, because:

  • I do not know what logic you are using.
  • This simplifies testing, expansion, etc.

For more information about LoadControl, see the documentation .

0
source

As for your problem with InvalidCastException, maybe this will help the MSDN page . You can try setting the class name of your control in the <%@ Control %> of the control.

0
source

Hope you find some tips from this topic - Dynamically changing a user control in ASP.Net

0
source

If you use the output cache, then LoadControl returns an instance of System.Web.UI.PartialCachingControl. You can then access the cached instance through your own CachedControl, which you must apply to the corresponding type created for UserControl.

0
source

All Articles