[asp.net] how to access master page control from content page

I have a master page which contains a label for status messages. I need to set the status text from different .aspx pages. How can this be done from the content page?

public partial class Site : System.Web.UI.MasterPage
{
    public string StatusNachricht
    {
        get
        {
            return lblStatus.Text;
        }
        set
        {
            lblStatus.Text = value;
        }
    }

    protected void Page_Load(object sender, EventArgs e)
    {            

    }
}

I have tried this, but was unsuccessful in making it work:

public partial class DatenAendern : System.Web.UI.Page
{
    var master = Master as Site;

    protected void Page_Load(object sender, EventArgs e)
    {               
        if (master != null)
        {
            master.setStatusLabel("");
        }
    }        

    protected void grdBenutzer_RowCommand(object sender, GridViewCommandEventArgs e)
    {           
            try
            {
                //some code

                if (master != null)
                {
                    master.setStatusLabel("Passwort erfolgreich geändert.");
                }
            }
            catch (Exception ex)
            {
                if (master != null)
                {
                    master.setStatusLabel("Passwort konnte nicht geändert werden!");
                }                                       
            }
        }
    }                   
}

This question is related to asp.net master-pages code-behind

The answer is


It Works

To find master page controls on Child page

Label lbl_UserName = this.Master.FindControl("lbl_UserName") as Label;                    
lbl_UserName.Text = txtUsr.Text;

If you are trying to access an html element: this is an HTML Anchor...

My nav bar has items that are not list items (<li>) but rather html anchors (<a>)

See below: (This is the site master)

<nav class="mdl-navigation">
    <a class="mdl-navigation__link" href="" runat="server" id="liHome">Home</a>
    <a class="mdl-navigation__link" href="" runat="server" id="liDashboard">Dashboard</a>
</nav>

Now in your code behind for another page, for mine, it's the login page...

On PageLoad() define this:

HtmlAnchor lblMasterStatus = (HtmlAnchor)Master.FindControl("liHome");
lblMasterStatus.Visible =false;

HtmlAnchor lblMasterStatus1 = (HtmlAnchor)Master.FindControl("liDashboard");
lblMasterStatus1.Visible = false;

Now we have accessed the site masters controls, and have made them invisible on the login page.


This is more complicated if you have a nested MasterPage. You need to first find the content control that contains the nested MasterPage, and then find the control on your nested MasterPage from that.

Crucial bit: Master.Master.

See here: http://forums.asp.net/t/1059255.aspx?Nested+master+pages+and+Master+FindControl

Example:

'Find the content control

Dim ct As ContentPlaceHolder = Me.Master.Master.FindControl("cphMain")

'now find controls inside that content

Dim lbtnSave As LinkButton = ct.FindControl("lbtnSave")


In Content page you can access the label and set the text such as

Here 'lblStatus' is the your master page label ID

Label lblMasterStatus = (Label)Master.FindControl("lblStatus");

lblMasterStatus.Text  = "Meaasage from content page";

You cannot use var in a field, only on local variables.

But even this won't work:

Site master = Master as Site;

Because you cannot use this in a field and Master as Site is the same as this.Master as Site. So just initialize the field from Page_Init when the page is fully initialized and you can use this:

Site master = null;

protected void Page_Init(object sender, EventArgs e)
{            
    master = this.Master as Site;
}

I have a helper method for this in my System.Web.UI.Page class

protected T FindControlFromMaster<T>(string name) where T : Control
{
     MasterPage master = this.Master;
     while (master != null)
     {
         T control = master.FindControl(name) as T;
         if (control != null)
             return control;

         master = master.Master;
     }
     return null;
}

then you can access using below code.

Label lblStatus = FindControlFromMaster<Label>("lblStatus");
if(lblStatus!=null) 
    lblStatus.Text = "something";

Examples related to asp.net

RegisterStartupScript from code behind not working when Update Panel is used You must add a reference to assembly 'netstandard, Version=2.0.0.0 No authenticationScheme was specified, and there was no DefaultChallengeScheme found with default authentification and custom authorization How to use log4net in Asp.net core 2.0 Visual Studio 2017 error: Unable to start program, An operation is not legal in the current state How to create roles in ASP.NET Core and assign them to users? How to handle Uncaught (in promise) DOMException: The play() request was interrupted by a call to pause() ASP.NET Core Web API Authentication Could not load file or assembly 'CrystalDecisions.ReportAppServer.CommLayer, Version=13.0.2000.0 WebForms UnobtrusiveValidationMode requires a ScriptResourceMapping for jquery

Examples related to master-pages

how to access master page control from content page Make absolute positioned div expand parent div height MVC 3: How to render a view without its layout page when loaded via ajax? a page can have only one server-side form tag Parser Error: '_Default' is not allowed here because it does not extend class 'System.Web.UI.Page' & MasterType declaration how to display none through code behind Where does error CS0433 "Type 'X' already exists in both A.dll and B.dll " come from? How to include Javascript file in Asp.Net page Master Page Weirdness - "Content controls have to be top-level controls in a content page or a nested master page that references a master page." Can I dynamically add HTML within a div tag from C# on load event?

Examples related to code-behind

How to call a C# function from JavaScript? how to access master page control from content page Set Text property of asp:label in Javascript PROPER way ASP.NET Web Application Message Box How to programmatically set the Image source Accessing a resource via codebehind in WPF Adding css class through aspx code behind Passing arguments to JavaScript function from code-behind The name 'controlname' does not exist in the current context ASP.net page without a code behind