简体   繁体   中英

How can I move an user control into a panel?

On .aspx I have this :

<%@ Register src="box/MyBox.ascx" tagname="MyBox" tagprefix="uc2" %>
<uc2:MyBoxID="MyBox1" runat="server" />

<asp:Panel ID="panelLeft" runat="server">

</asp:Panel>

<asp:Panel ID="panelRight" runat="server">

</asp:Panel>    

and I'd like, on the aspx.cs , doing somethings like this :

if (condition)
{
    panelLeft.Controls.Add(MyBox1);
}
else
{
    panelRight.Controls.Add(MyBox1);
}

but seems I can't do it! Why? And how can I do it?

You'll have to use LoadControl to create the control server-side.

Control myBox1 = LoadControl("~/box/MyBox.ascx");
if (condition) 
{ 
    panelLeft.Controls.Add(myBox1); 
} 
else 
{ 
    panelRight.Controls.Add(myBox1); 
} 

If for some reason adding the control using LoadControl doesn't fit with the approach you want to take, you can achieve something similar by adding two copies of the user control into the markup in the two positions where you would like them. You can then toggle visibility in the code behind in your conditional logic.

For example, an ASPX like this:

<%@ Register src="box/MyBox.ascx" tagname="MyBox" tagprefix="uc2" %>


<asp:Panel ID="panelLeft" runat="server">
    <uc2:MyBoxID="MyBox1" runat="server" />    
</asp:Panel>

<asp:Panel ID="panelRight" runat="server">
    <uc2:MyBoxID="MyBox2" runat="server" />        
</asp:Panel>    

And then in the code behind you can toggle visibility:

MyBox1.Visible = condition;
MyBox2.Visible = !MyBox1.Visible;    

However, you are then loading two different copies of the user control onto the page and your code would then have to know which user control to access, instead of always accessing 'MyBox1'. You might need a property in your code behind that hides that check for you, something like :

private MyBox MyBox{
   get { return condition ? MyBox1 : MyBox2; }
}
if (condition) 
{ 
   this.panelLeft.Controls.Add(mybox1);
} 
else 
{ 
    this.panelRight.Controls.Add(myBox1); 
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM