Is there a way to access page controls from user control . I have some controls in my page and i want to access these controls from the user control .
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
回答1:
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;
}
Example
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;
}
回答2:
There are actually several ways to accomplish this:
Create a public property in your user control
public Button PageButton { get; set; }
Then assign it in the page's OnInit or OnLoad method
myUserControl.PageButton = myPageButton;
You can make the control public and unbox Page:
public Button PageButton { get { return this.myPageButton; } }
In the user control:
MyPage myPage = (MyPage)this.Page;
myPage.PageButton.Text = "Hello";
The slowest, but easiest way would be to use FindControl:
this.Page.FindControl("myPageButton");
回答3:
Parent.FindControl("hdnValue")
回答4:
its work for me :
I declare Label in My .aspx
page
<asp:Label ID="lblpage" runat="server" Text="this is my page"></asp:Label>
<asp:Panel ID="pnlUC" runat="server"></asp:Panel>
In .aspx.cs
I have add UserControl through Panel
UserControl objControl = (UserControl)Page.LoadControl("~/ts1.ascx");
pnlUC.Controls.Add(objControl);
and access from in .ascx
UserControl like this :
Page page = this.Page;
Label lbl = page.FindControl("lblpage") as Label;
string textval = lbl.Text;