How to access page controls from user control?

后端 未结 4 1974
长情又很酷
长情又很酷 2020-12-18 10:08

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 .

相关标签:
4条回答
  • 2020-12-18 10:23

    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;
    
    0 讨论(0)
  • 2020-12-18 10:32

    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");
    
    0 讨论(0)
  • 2020-12-18 10:34
    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;
    }
    
    0 讨论(0)
  • 2020-12-18 10:40
        Parent.FindControl("hdnValue")
    
    0 讨论(0)
提交回复
热议问题