Thursday, February 10, 2011

How to reference and update controls in the MasterPage:


There are two cases :

a.Control outside the ContentPlaceHolder in the MasterPage.
b.Control  inside the ContentPlaceHolder in the MasterPage.

a. Control outside the ContentPlaceHolder in the MasterPage:
1. Open Visual Studio and create a new website by using the ASP.NET Web Site template
in either C# or Visual Basic.

2.Add a MasterPage .

3.Now add a Label control outside the Content Place Holder :
<body>
    <form id="form1" runat="server">
    <div>
        <asp:ContentPlaceHolder id="ContentPlaceHolder1" runat="server">
        </asp:ContentPlaceHolder>

        <asp:Label ID="masterlabel" runat="server" Text="Label"></asp:Label>
    </div>
    </form>
</body>
</html>


4.Now just add ContentPage with select master page property checked as shown in the figure.A window popup ,select master page where you add Label control.

5.In the content page add this code in the Page_Load Event.

protected void Page_Load(object sender, EventArgs e)
    {
        Label mylabel = (Label)Master.FindControl("masterlabel");
        if (mylabel != null)
        {
            mylabel.Text = "Text changed";
        }
          
    }

Debug the program and run it .
Notes that a label in masterpage get called in contentPage and updated from contentPage.



b.Control  inside the ContentPlaceHolder in the MasterPage.

1. Add a MasterPage and this time add a label inside the cContentPlaceHolder.



<body>
    <form id="form1" runat="server">
    <div>
        <asp:ContentPlaceHolder id="ContentPlaceHolder1" runat="server">
         <asp:Label ID="masterlabel" runat="server" Text="Label"></asp:Label>
        </asp:ContentPlaceHolder>

      
    </div>
    </form>
</body>



2.Now add a ContentPage with selectmasterpage Property checked.Select masterpage where you add label inside the ContenPlaceHolder.

3. Now add this code to Page_Load event :

ContentPlaceHolder myContentPlaceHolder;
    Label mylabel;
    myContentPlaceHolder= (ContentPlaceHolder)Master.FindControl("ContentPlaceHolder1");

    if(myContentPlaceHolder != null)
    {
       mylabel = (Label) myContentPlaceHolder.FindControl("masterlabel");

        if(mylabel != null)
        {
            mylabel.Text = "Text Changed";
        }
    }


Debug the program and run it .
Notes that a label in masterpage get called in contentPage and updated from contentPage.