In this article, we shall learn how to access Master page control from the content page.
Introduction
Master page allows us to share the common content as well as layout to multiple pages. The best example is to show same header and footer and the same layout across different pages of the website. For example on ITFunda.com - an ASP.NET online training website you can notice that all pages have same header and footer but in between content is different. The layout in which header and footer exists is the master page (.master) and rest content comes from the content page (.aspx page).
In this article, let us learn how to access Master page control from the content page. To demonstrate this I have created a demo page.
Get hundreds of .NET Tips and Tricks and ASP.NET Online training here.
In some scenario, we need to access master page controls from the content page, that can be done by
following this approach.
Below is my master page (MasterPage.master).
MASTER PAGE
<%@ Master Language="C#" AutoEventWireup="true" CodeFile="MasterPage.master.cs" Inherits="NestedMasterPage_MasterPage" %>
<!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></title>
<asp:ContentPlaceHolder ID="ContentPlaceHolder2" runat="server">
</asp:ContentPlaceHolder>
</head>
<body>
<form id="form2" runat="server">
<div>
<p style="color: Red;">This text is from parent master page</p>
<asp:ContentPlaceHolder ID="ContentPlaceHolder3" runat="server">
</asp:ContentPlaceHolder>
<asp:Label ID="lblMasterMessage" runat="server" EnableViewState="false" />
</div>
</form>
</body>
</html>
ASPX PAGE
<%@ Page Title="" Language="C#" MasterPageFile="~/NestedMasterPage/MasterPage.master"
AutoEventWireup="true" CodeFile="AccessMasterPageLabel.aspx.cs" Inherits="NestedMasterPage_AccessMasterPageLabel" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="Server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="Server">
</asp:Content>
ASPX PAGE CODE BEHIND
protected void Page_Load(object sender, EventArgs e)
{
Label lblMaster = (Label)this.Master.FindControl("lblMasterMessage");
if (lblMaster != null)
{
lblMaster.Text = "This text is written from the content page.";
}
}
In the above code snippet, we have an asp:Label control on the master page. From the code behind of the content page, we are trying to access the Master page using this.Master.FindControl method. It’s ideal to check for the null value for that variable (to ensure that the control is found successfully) and then we have specified a string for that label text.
OUTPUT

As displayed in the above image, you can see that text specified to the Label control from the content page is appearing on the output page.
Hope this article will be useful. Keep reading!
Stay tuned for the next article!