简体   繁体   English

在具有母版页的页面上查找控件

[英]Find a control on a page with a master page

I have to find a Control in an aspx page bound to a master page. 我必须在绑定到母版页的aspx页中找到一个Control

The master page contains: 母版页包含:

<asp:ContentPlaceHolder ID="MainContent" runat="server"/>               

The content page contains: 内容页面包含:

<asp:Content ID="Content1" ContentPlaceHolderID="HeadContent" Runat="Server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" Runat="Server">
</asp:Content>

I added a Table with ID formtable as a child of Content2 . 我添加了一个ID formtable Table作为formtable的子Content2

I tried to use the following code to access the Table , but the code returns null : 我尝试使用以下代码访问Table ,但代码返回null

protected void Ok_Click(object sender, EventArgs e)
{
    Table tblForm = this.FindControl("MainContent").FindControl("formtable") as Table;                 
}

How can I access the Table ? 如何访问Table

Try this 尝试这个

Table tblForm = this.Master.FindControl("MainContent").FindControl("formtable") as Table; 

Checkout this Control ID Naming in Content Pages for more details 在内容页面中检查此控件ID命名以了解更多详细信息

Working with findControl() cause complications sometimes. 使用findControl()有时会导致并发症。 It is easier to define a public property for that control in master page and then access control through the property. 在母版页中为该控件定义一个公共属性,然后通过该属性访问控件会更容易。

you should add this line in child page: 您应该在子页面中添加以下行:

<%@ MasterType VirtualPath="~/MasterPage.master" %>

What context are you in when you are trying to do this? 当您尝试执行此操作时,您处于什么环境? Are you in the codebehind of the individual page? 您是否在单个页面的代码后面?

If you are it should be Content1.FindControl("formtable") as Table and that would be it. 如果是的话,应该为Content1.FindControl("formtable") as Table

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM