嵌套的Masterpages和.FindControl

时间:2009-10-16 13:53:28

标签: c# asp.net master-pages findcontrol

在一个站点上,我只使用单级主页,在使用该主页的页面中,我可以执行此操作.Master.FindControl(“controlName”)来访问该控件。工作正常。

但是,在具有两个母版页级别的网站上使用相同的代码。以MainMaster为主的MainMaster和SpecificMaster。

因此,在使用SpecificMaster的页面上,FindControl为对象返回null。我看到的唯一区别是主页的嵌套。

当我设置断点并查看page.Master时,它显示了SpecificMaster,而SpecificMaster正确显示MainMaster作为其主节点,但FindControl仍然失败。

当我在IE中查看源代码时,控件被正确命名,没有.NET正在进行。

这里有什么想法吗?

TIA!

7 个答案:

答案 0 :(得分:18)

当您嵌套母版页时,您将获得一个额外的容器“内容”,您需要查看。

因此,如果您尝试使用给定子页面中的FindControl,通常的方法就会产生以下影响:

Label myLabel = (Label)this.Master.FindControl("myLabel");
myLabel.Text = "Success!";

由于我们有一个嵌套的母版页,子母版中有“myLabel”,因此该控件将包含在内容控件中。

因此,这会将代码更改为:

ContentPlaceHolder ph = (ContentPlaceHolder)this.Master.Master.FindControl("yourContentPane");

Label myLabel = (Label)ph.FindControl("myLabel");
myLabel.Text = "Success!";

并在 VB.NET

Dim ph As ContentPlaceHolder = DirectCast(Me.Master.Master.FindControl("yourContentPane"), ContentPlaceHolder)

Dim myLabel As Label = DirectCast(ph.FindControl("myLabel"), Label)
myLabel.Text = "Success!"

子页面中的内容将加载到第一个母版页控件中,随后将其加载到祖父母母版页中。

答案 1 :(得分:3)

你试过this.Master.Master.FindControl("controlname");吗?

答案 2 :(得分:0)

它也适用于跨页回发:

ContentPlaceHolder ph =(ContentPlaceHolder)PreviousPage.Master.FindControl(“ContentPlaceHolder”);

string txt =((TextBox)(ph.FindControl(“UserTextBox”)))。Text;

答案 3 :(得分:0)

我通常这样做:

(TextBox)this.Master.FindControl("ContentplaceHolder1").FindControl("TextBox1");

答案 4 :(得分:0)

HyperLink hl = (HyperLink)Master.Master.FindControl("HyperLink3");

这是从嵌套母版页中查找控件的最简单方法。

答案 5 :(得分:0)

我的情况如下。不确定此设置是否正确,但它允许我设置master-submaster页面,并且能够找到控件。

MasterPage-> SubMasterPage - > ASPX页面

母版:

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

SubMasterPage:

<asp:Content ID="ModuleMainContent" ContentPlaceHolderID="MasterPageContentPlaceHolder" runat="server">
<asp:ContentPlaceHolder ID="MainContent" runat="server">
</asp:ContentPlaceHolder>

ASPX.cs:

ContentPlaceHolder MainContent = (ContentPlaceHolder)this.Master.Master.FindControl("MasterPageContentPlaceHolder").FindControl("MainContent");
    TextBox var_type = MainContent.FindControl("air") as TextBox;

答案 6 :(得分:0)

尝试

    string txt = ((TextBox)this.Master.FindControl("ContentIDName").FindControl("TextBox1")).Text;
相关问题