Reputation: 11393
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 .
Upvotes: 6
Views: 58272
Reputation: 10095
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;
}
Upvotes: 15
Reputation: 3558
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;
Upvotes: 1
Reputation: 23113
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");
Upvotes: 12