How to access page controls from user control?

2020-02-11 09:14发布

问题:

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;