How do I access page controls from a custom control?
4 answers
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;
}
+11
source to share
There are actually several ways to do this:
Create public property in custom control
public Button PageButton { get; set; }
Then assign it in the OnInit page or OnLoad method
myUserControl.PageButton = myPageButton;
You can make it public and unbox Page:
public Button PageButton { get { return this.myPageButton; } }
In a user control:
MyPage myPage = (MyPage)this.Page;
myPage.PageButton.Text = "Hello";
The slowest but easiest way is to use FindControl:
this.Page.FindControl("myPageButton");
+10
source to share
its working for me:
I declare a shortcut on the page .aspx
<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 add a UserControl viaPanel
UserControl objControl = (UserControl)Page.LoadControl("~/ts1.ascx");
pnlUC.Controls.Add(objControl);
and access from .ascx
UserControl like this:
Page page = this.Page;
Label lbl = page.FindControl("lblpage") as Label;
string textval = lbl.Text;
+1
source to share