C# – ASP.NET Dynamically Change User Control Source

asp.netcnetuser-controlsvisual studio

The Scenario

I have an ASP.Net Web Project that uses a master page.
This master page contains a menu in the form of a user control.
Sometimes I want to dynamically change this to use a different type of menu user control.

The current code to register the user control

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

Inside the body tags

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

The Question

Is there anyway I can change the "SRC" attribute in the register code dynamically to use a different user control?!

Help greatly appreciated

EDIT:

Tried This Code But I Receive An 'Invalid Cast Exception'

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

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

Best Answer

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

UserControls_header3 uh3 = (UserControls_header3)this.LoadControl(header3);
phHeaderControls.Controls.Add(uh3);
Related Topic