开发者

Change UserControl template at runtime

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开发者_如何学JAVA same usercontrol codebehind, it would just be a different template.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜