简体   繁体   English

如何将用户控件移动到面板中?

[英]How can I move an user control into a panel?

On .aspx I have this : .aspx我有这个:

<%@ 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 : 我想在aspx.cs做这样的事情:

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. 您必须使用LoadControl来创建控件服务器端。

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. 如果由于某种原因,使用LoadControl添加控件不适合您要采用的方法,则可以通过将用户控件的两个副本添加到标记中您希望的两个位置来实现相似的目的。 You can then toggle visibility in the code behind in your conditional logic. 然后,您可以在条件逻辑中的代码后面切换可见性。

For example, an ASPX like this: 例如,像这样的ASPX:

<%@ 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'. 但是,您随后将用户控件的两个不同副本加载到页面上,然后您的代码将必须知道要访问哪个用户控件,而不是始终访问“ 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); 
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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