[英]How to access page controls from user control?
有没有办法从用户控件访问页面控件。 我的页面中有一些控件,我想从用户控件访问这些控件。
YourControlType ltMetaTags = null;
Control ctl = this.Parent;
while (true)
{
ltMetaTags = (ControlType)ctl.FindControl("ControlName");
if (ltMetaTags == null)
{
ctl = ctl.Parent;
if(ctl.Parent == null)
{
return;
}
continue;
}
break;
}
例子
System.Web.UI.WebControls.Literal ltMetaTags = null;
Control ctl = this.Parent;
while (true)
{
ltMetaTags = (System.Web.UI.WebControls.Literal)ctl.FindControl("ltMetaTags");
if (ltMetaTags == null)
{
if(ctl.Parent == null)
{
return;
}
ctl = ctl.Parent;
continue;
}
break;
}
实际上有几种方法可以实现这一点:
在用户控件中创建公共属性
public Button PageButton { get; set; }
然后在页面的OnInit或者OnLoad方法中赋值
myUserControl.PageButton = myPageButton;
您可以公开控件并取消装箱页面:
public Button PageButton { get { return this.myPageButton; } }
在用户控件中:
MyPage myPage = (MyPage)this.Page;
myPage.PageButton.Text = "Hello";
最慢但最简单的方法是使用 FindControl:
this.Page.FindControl("myPageButton");
Parent.FindControl("hdnValue")
它对我的工作:
我在我的.aspx
页面中声明 Label
<asp:Label ID="lblpage" runat="server" Text="this is my page"></asp:Label>
<asp:Panel ID="pnlUC" runat="server"></asp:Panel>
在.aspx.cs
,我通过Panel
添加了 UserControl
UserControl objControl = (UserControl)Page.LoadControl("~/ts1.ascx");
pnlUC.Controls.Add(objControl);
并从.ascx
UserControl 中访问,如下所示:
Page page = this.Page;
Label lbl = page.FindControl("lblpage") as Label;
string textval = lbl.Text;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.