如何从asp.net中的母版页访问内容页面控件

时间:2011-02-12 18:03:56

标签: asp.net

等内容页面访问母版页控件非常容易
protected void Page_Load(object sender, EventArgs e)
{
    // content page load event
    DropDownList thisDropDown = this.Master.FindControl("someDropDown") as DropDownList;
    userLabel.Text = thisDropDown.SelectedValue;
}

但我如何从母版页访问内容页面的控件。假设内容页面中有一个文本框,主页面中有一个按钮。我希望当我点击母版页按钮然后我想在母版页标签的内容页面中显示文本框的文本。如何实现它。请帮我提供代码示例。感谢。

7 个答案:

答案 0 :(得分:34)

在母版页按钮中,点击事件应通过以下方式访问页面内容: -

protected void Button1_Click(object sender, EventArgs e)
{
    TextBox TextBox1 = (TextBox)ContentPlaceHolder1.FindControl("TextBox1");
    if (TextBox1 != null)
    {
        Label1.Text = TextBox1.Text;
    }
}

答案 1 :(得分:3)

已经有一段时间了,但我相信您可以使用ContentPlaceHolder作为参考:

Control control = this.myContentPlaceHolder.FindControl("ContentPageControlID");

答案 2 :(得分:3)

在我看来,最好从Master页面使用事件加注,并在contenet页面中捕获此事件,例如,更改此页面上的某些contenet。主要优点是可重用性。将来,您可能希望从主页面更改其他内容页面上的内容,在这种情况下,您应该只在此内容页面中添加事件处理程序,而无需更改母版页上的代码。在这种方法中,您无需从某个内容页面硬编码控件名称。而且你根本不应该为某些内容的控制添加依赖。

例如,您可以找到here的实施示例。

答案 3 :(得分:1)

您应该从母版页中查找contentplaceholder,然后在母版页的子项中查找contentplaceholder

this.Page.Master.FindControl("ContentPlaceHolder1").FindControl("controlAFromPage");

答案 4 :(得分:0)

您可以使用以下方法找到控件:

ContentPlaceHolder contentPage = Page.MasterPage.FindControl("ContentPlaceHolder1") as ContentPlaceHolder;
Label lblHead =(Label)contentPage.FindControl("lblHeading");
Response.Write(lblHead.Text);

来源: http://xpode.com/ShowArticle.aspx?ArticleId=629

答案 5 :(得分:0)

Site.Master中的C#代码:

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

Site.Master.cs中的代码:

public partial class SiteMaster : MasterPage
{
    protected void Page_Load(object sender, EventArgs e)
    {          
        ToolkitScriptManager1.RegisterPostBackControl(this.MainContent.FindControl("btnOnDefaultPage"));            
    }
}

这是一个示例,如何从Site.Master.cs引用Default.aspx上的客户端控件

答案 6 :(得分:-1)

试试此代码

Page.Master.FindControl("MainContent").FindControl("DivContainer_MyProfile").Visible = True