15
votes

it is very easy to access master page control from content page like

protected void Page_Load(object sender, EventArgs e)
{
    // content page load event
    DropDownList thisDropDown = this.Master.FindControl("someDropDown") as DropDownList;
    userLabel.Text = thisDropDown.SelectedValue;
}

but how could i access controls of content page from master page. suppose a textbox there in content page and one button is there in master page. i want that when i will click on master page button then i want to show the text of textbox in the content page in the label of master page. how to achieve it. please help me with code sample. thanks.

7

7 Answers

35
votes

In master page button click event should access page contents by:-

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

It's been a while, but I believe you can do so by using the ContentPlaceHolder as a reference:

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

In my opinion it even better to use event raise from Master page and catch this event in contenet page for changing some contenet on this page, for instance. The main advantage is reusability. In future you may want to change content on other content page from the Master page and in this case you should only add event handler to this content page without changing code on master page. Within such approach you needn't hardcode control name from some content page. And moreover you shouldn't add dependency for some content's control at all.

A sample of implementation you can find here, for example.

1
votes

you should look for contentplaceholder from master page then contentplaceholder in child of the master page

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

You can find control by using this:

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

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

0
votes

C# code within Site.Master:

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

Code within Site.Master.cs:

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

This is an example how a client control on the Default.aspx is referenced from a Site.Master.cs

-1
votes

Try this code

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