Access Master Page Controls from ASP.NET Page

 

Whenever your Asp.Net web application using Master Pages, you may have requirement to access Master Page content also from your child pages. For example Asp.Net Master page has some asp.net controls and you have to change its content dynamically based on content page event.

 

You can access Master Page controls from your child Page by FindControl() Method of Master Class. For example you have Master Page Master.master as shown below which has one Label control and one Literal control.

 

<%@ Master Language="C#" AutoEventWireup="true" CodeFile="Master.master.cs" Inherits="Master" %>

 

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

 

<html xmlns="http://www.w3.org/1999/xhtml">

 

<head runat="server">

 

    <title>Access Master Page Controls from Asp.Net Page</title>

 

    <asp:ContentPlaceHolder id="head" runat="server">

 

    </asp:ContentPlaceHolder>

 

</head>

 

<body>

 

    <form id="form1" runat="server">

 

    <div>

 

        <asp:ScriptManager ID="ScriptManager1" runat="server" />

 

        <asp:Label ID="lblMaster" runat="server"></asp:Label><br />

 

        <asp:Literal ID="litMaster" runat="server"></asp:Literal><br />

 

        <asp:ContentPlaceHolder id="ContentPlaceHolder1" runat="server">       

 

        </asp:ContentPlaceHolder>

 

    </div>

 

    </form>

 

</body>

 

</html>

 

 And You can access these Label and Literal control from your child page Default.aspx for button click event as shown below.

 

using System; 

using System.Web.UI.WebControls; 

 

public partial class _Default : System.Web.UI.Page 

{ 

    protected void Page_Load(object sender, EventArgs e) 

    {

 

    }  

     protected void btn_Click(object sender, EventArgs e) 

    { 

        Literal lit = this.Master.FindControl("litMaster") as Literal; 

        Label lbl = this.Master.FindControl("lblMaster") as Label;

 

        lit.Text = "This is Literal Control in Master Page"; 

        lbl.Text = "This is Label Control in Master Page"; 

    } 

}

 

As shown above, by using this.Master.FindControl() method you can access asp.net master page controls from its asp.net web page.

                                                                                                                    AccessMasterPageControls.zip (3.80 kb)