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

发布于 2024-09-19 17:31:53 字数 812 浏览 1 评论 0原文

我必须在绑定到母版页的 aspx 页面中找到一个 Control

母版页包含:

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

内容页包含:

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

我添加了一个带有 ID formtableTable 作为 Content2 的子项。

我尝试使用以下代码访问Table,但代码返回null

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

如何访问Table

I have to find a Control in an aspx page bound to a master page.

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.

I tried to use the following code to access the Table, but the code returns null:

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

How can I access the Table?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

缺⑴份安定 2024-09-26 17:31:53

试试这个

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

查看这个 内容中的控件 ID 命名页面了解更多详情

Try this

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

Checkout this Control ID Naming in Content Pages for more details

櫻之舞 2024-09-26 17:31:53

当您尝试执行此操作时,您处于什么环境中?您是否在单个页面的代码隐藏中?

如果是的话,应该是 Content1.FindControl("formtable") as Table 就这样了。

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.

独孤求败 2024-09-26 17:31:53

使用 findControl() 有时会导致复杂化。
在母版页中为该控件定义公共属性,然后通过该属性访问控件会更容易。

您应该在子页面中添加此行:

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

Working with findControl() cause complications sometimes.
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" %>
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文