如何从用户控件访问页面控件?

Any*_*are 3 c# asp.net user-controls

有没有办法从用户控件访问页面控件.我的页面中有一些控件,我想从用户控件访问这些控件.

Pan*_*kaj 13

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;
}
Run Code Online (Sandbox Code Playgroud)

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;
}
Run Code Online (Sandbox Code Playgroud)


Chr*_*ler 10

实际上有几种方法可以做到这一点:

在用户控件中创建公共属性

public Button PageButton { get; set; }
Run Code Online (Sandbox Code Playgroud)

然后在页面的OnInit或OnLoad方法中分配它

myUserControl.PageButton = myPageButton;
Run Code Online (Sandbox Code Playgroud)

您可以将控件设为public和unbox页面:

public Button PageButton { get { return this.myPageButton; } }
Run Code Online (Sandbox Code Playgroud)

在用户控件中:

MyPage myPage = (MyPage)this.Page;
myPage.PageButton.Text = "Hello";
Run Code Online (Sandbox Code Playgroud)

最慢但最简单的方法是使用FindControl:

this.Page.FindControl("myPageButton");
Run Code Online (Sandbox Code Playgroud)