views:

16

answers:

1

Is it possible to change the ascx file used by a usercontrol at runtime?

For example in my page i have

<ctl:SampleControl runat="server" />

in the web.config I have

<controls>
<add tagPrefix="ctl" tagName="SampleControl" src="~/UserControls/SampleControl.ascx" />
</controls>

At runtime I would like to be able to change the ascx to another path, it would still be inheriting from the same usercontrol codebehind, it would just be a different template.

A: 

Probably the best thing to do here is to not encode the filename of the "default" .ascx file in your web.config. It will make your life harder. Always do that determination at runtime, like this for instance:

In your .aspx file:

<asp:PlaceHolder runat="server" ID="samplePH" />

In the code-behind:

string file = "~/UserControls/SampleControl.ascx";
if (condition)
    file = "~/UserControls/OtherControl.ascx";
UserControl uc = (UserControl)LoadControl(file);  // from System.Web.UI.TemplateControl.
samplePH.Controls.Clear();
samplePH.Controls.Add(uc);

But, be aware that in order for post-backs to work correctly, you need to instantiate the same control that was loaded on the last request, early in the page lifecycle -- typically the Init stage. This will ensure that viewstate is correctly parsed. Then, further down in your event handler, PreRender, etc. lifecycle steps, you can use the above code to load the UserControl for the current request.

If you really do need to encode a default page setting in a configuration file (for cases where end-users may want to change it), consider doing it in an app.config rather than buried away in a <controls> section of a web.config.

Documentation for the TemplateControl.LoadControl(string) method: http://msdn.microsoft.com/en-us/library/system.web.ui.templatecontrol.loadcontrol.aspx

Warren
Hi Warren, that is a potential solution but it has a few problems for me. First of all, i dont really want to tie the usercontrol to the codebehind, ultimately i want it to just be dropped in to a page.This then brings about the problem of passing values to the usercontrol, if i was to use properties i could pop it in the page with <uc value="<%= Blah%>"> but if the usercontrol is hidden behind logic then that won't be feasible.
dnolan