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

6
有没有一种方法可以从用户控件访问页面控件。我在页面上有一些控件,我想从用户控件中访问这些控件。

11
实际上你不需要-真的不需要...我承认有些原因可能会让你想这样做(有过这样的经历),但从根本上讲,这是一种反模式-用户控件应该在独立的环境中工作,如果它需要数据,你需要传递这些数据,如果它需要影响周围的东西,那么它应该引发事件。这也可以更好地测试出一个能在独立环境下运行的控件。虽然没有绝对的规定,但你的用例可能完全合理...但我希望你认真考虑。 - Murph
4个回答

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

例子

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

12

实际上有几种方法可以完成这个任务:

在你的用户控件中创建一个公共属性。

public Button PageButton { get; set; }

然后在页面的OnInit或OnLoad方法中进行赋值。

myUserControl.PageButton = myPageButton;
你可以将控件公开,并取消封箱 Page:
public Button PageButton { get { return this.myPageButton; } }
在用户控件中:
MyPage myPage = (MyPage)this.Page;
myPage.PageButton.Text = "Hello";

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

this.Page.FindControl("myPageButton");

获取“空引用异常”((Label)this.Page.FindControl("mylabel")).ID; - Anyname Donotcare
1
@just_name - 开始一个新问题或编辑此问题并包含您的源代码。 - Chris Gessler
在运行时创建用户控件的代码如下: MyBaseControl ctrl = (MyBaseControl)LoadControl("UserControls/" + page_new_name);pnl_PageNew_UC.Controls.Add(ctrl); - Anyname Donotcare
在页面上搜索控件并不意味着一定能找到你要找的内容。FindControl() 方法只会在当前子集合中进行搜索。如果你不确定从树的哪个位置开始搜索,就需要进行递归搜索。http://sharpertutorials.com/recursive-findcontrol/ - Pauli Østerø
@PauliØsterø - 如果提问者问“如何在另一个控件中递归搜索控件”,这将非常有帮助,但如果开发人员忘记了他放置控件的位置,也很好知道。 - Chris Gessler
显示剩余4条评论

3
    Parent.FindControl("hdnValue")

2
父控件可能是另一个用户控件。最好使用 this.Page。 - Chris Gessler
1
@ChrisGessler 在页面上搜索控件并不保证自动找到你要找的内容。页面是一个控件,就像UserControl是一个控件一样,FindControl()是一个方法,只会在当前子集合中搜索。如果你不知道从树的哪个位置开始搜索,你需要进行递归搜索。http://sharpertutorials.com/recursive-findcontrol/ - Pauli Østerø

1

它对我有用:

我在我的.aspx页面中声明了标签。

  <asp:Label ID="lblpage" runat="server" Text="this is my page"></asp:Label>
  <asp:Panel ID="pnlUC" runat="server"></asp:Panel>

.aspx.cs 中,我通过 Panel 添加了 UserControl。
   UserControl objControl = (UserControl)Page.LoadControl("~/ts1.ascx");
   pnlUC.Controls.Add(objControl);

并且可以像这样从 .ascx 用户控件中访问:

 Page page = this.Page;
 Label lbl = page.FindControl("lblpage") as Label;
 string textval = lbl.Text;

像这样在运行时创建的用户控件 - Anyname Donotcare
MyBaseControl ctrl = (MyBaseControl)LoadControl("UserControls/" + page_new_name); pnl_PageNew_UC.Controls.Add(ctrl);` - Anyname Donotcare
@just_name。我通过面板添加用户控件,然后使用以下代码可以访问标签值。建议尝试一下。 - Jignesh Rajput

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接