如何从用户控件访问页面控件?
有没有办法从用户控件访问页面控件。 我的页面中有一些控件,我想从用户控件访问这些控件。
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和unbox页面:
public Button PageButton { get { return this.myPageButton; } }
在用户控件中:
MyPage myPage = (MyPage)this.Page; myPage.PageButton.Text = "Hello";
最慢但最简单的方法是使用FindControl:
this.Page.FindControl("myPageButton");
它的工作对我来说:
我在My .aspx
页面中声明了Label
在.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;
Parent.FindControl("hdnValue")