Question

I am using nested master pages where i want to use Label control from nested master page and update its text. but it is not accessing. When i removed outer master page then it is working fine. Following is the markup and code.

OUTER MASTER

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

NESTED MASTER

<%@ Master Language="C#" AutoEventWireup="true" CodeBehind="RoasterMaster.master.cs" Inherits="Roster.RoasterMaster"  MasterPageFile="~/Site.Master" %>
<%@ MasterType VirtualPath ="~/Site.Master" %>

CONTENT PAGE

<%@ Page Language="C#" AutoEventWireup="true" Inherits="RequestsView" CodeBehind="ViewRequestsByPM.aspx.cs" MasterPageFile ="~/Roaster/RoasterMaster.Master" Title ="Roaster- View Requests by PM" %>
<%@ MasterType VirtualPath ="~/Roaster/RoasterMaster.Master" %>

CONTENT PAGE CODE

protected void Page_Load(object sender, EventArgs e)
{


    Label lblTitle = new Label();

    lblTitle =(Label)Master.FindControl("lblTitle");
    lblTitle.Text = "View Roaster Request";
}

What is going wrong with the implementation. Please help. Thanks

Was it helpful?

Solution

You can add the below code snippet in

NESTED MASTER PAGE

public string PageTitle { get; set; } // In page_load
lblTitle.Text = PageTitle;

CONTENT PAGE CODE

this.Master.PageTitle = "YOUR TEXT";

This will work for you...

OTHER TIPS

Assuming that your label is in Roster master page, you can simply add method to set the text in master page code behind. For example,

in RoasterMaster.master.cs

public void SetTitle(string value)
{
   this.lblTitle = value;
}

And in content page code

Master.SetTitle("View Roaster Request");

In case, your label is in outer master then you can similarly forward the call to the outer master from roster master code.

EDIT
Your code does not work in nested master case scenarios because Master page contents get added within page control hierarchy with different naming container. FindControl method does not span multiple naming containers which is the case here - because of nesting you have nested naming containers. Page.Master would give you outer naming container but your label might be lying in inner naming container. One of the way, is to write your own find control implementation that will recurs within the control tree but really it does not make sense - I would rather use above code which is more efficient and more importantly better maintainable.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top