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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10053541/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 12:16:00  来源:igfitidea点击:

How to access page controls from user control?

c#asp.netuser-controls

提问by Anyname Donotcare

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 .

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

采纳答案by Pankaj

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

回答by Kunal Shah

    Parent.FindControl("hdnValue")

回答by Chris Gessler

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

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

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:

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

this.Page.FindControl("myPageButton");

回答by Jignesh Rajput

its work for me :

它对我的工作:

I declare Label in My .aspxpage

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

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

In .aspx.csI have add UserControl through Panel

.aspx.cs我通过添加 UserControlPanel

   UserControl objControl = (UserControl)Page.LoadControl("~/ts1.ascx");
   pnlUC.Controls.Add(objControl);

and access from in .ascxUserControl like this :

并从.ascxUserControl 中访问,如下所示:

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