Hello (sorry for the poor title)
I have a user control which loads different additional user controls based on some conditions like this:
<%@ Control Language="C#" AutoEventWireup="true" CodeFile="SubPage.ascx.cs" Inherits="SubPage" %>
<%@ Register Src="<srcA>" TagName="A" TagPrefix="CTRL" %>
<%@ Register Src=">srcB>" TagName="B" TagPrefix="CTRL" %>
<% if (someValue == 1) { %>
Loading user control A..
<CTRL:A runat="server" />
<% } else { %>
Loading user control B..
<CTRL:B runat="server" />
<% } %>
The result will look correct; the expected content is displayed. But I noticed that even though someValue != 1 and control B is displayed, control A is still loaded behind the scenes (page load is called).
Why is this? And what would be a better approach? Thanks.
Page_Load is called because you handle this event. Don't try to load them in this way but use the Visible-Property instead from codebehind.
Expose a public function that the controller(in your case SubPage.ascx
) calls after it changed the visible state to load the content of the UserControl. Controls that aren't visible won't be rendered as html at all.
Loading controls dynamically if you don't really need can cause unnecessary ViewState- or Event-Handling issues. Here are some other disadvantages mentioned regarding dynamic UserControls.
You need to call LoadControl
method instead
<% if (someValue == 1) { %>
Loading user control A..
Page.LoadControl(("~\ExampleUserControl_A.ascx");
<% } else { %>
Loading user control B..
this.LoadControl(("~\ExampleUserControl_B.ascx");
<% } %>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With