有没有一种方法可以从用户控件访问页面控件。我在页面上有一些控件,我想从用户控件中访问这些控件。
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;
你可以将控件公开,并取消封箱 Page:public Button PageButton { get { return this.myPageButton; } }
在用户控件中:MyPage myPage = (MyPage)this.Page;
myPage.PageButton.Text = "Hello";
最慢但最简单的方法是使用FindControl:
this.Page.FindControl("myPageButton");
MyBaseControl ctrl = (MyBaseControl)LoadControl("UserControls/" + page_new_name);pnl_PageNew_UC.Controls.Add(ctrl);
- Anyname Donotcare Parent.FindControl("hdnValue")
它对我有用:
我在我的.aspx
页面中声明了标签。
<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
用户控件中访问:
Page page = this.Page;
Label lbl = page.FindControl("lblpage") as Label;
string textval = lbl.Text;