How to access page controls from user control?

后端 未结 4 1978
长情又很酷
长情又很酷 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: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");
    

提交回复
热议问题