How to access page controls from user control?

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 .

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 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;
}

Method 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");

Method 3

    Parent.FindControl("hdnValue")

Method 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;


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x