SteveU
SteveU

Reputation: 111

c# Accessing MasterPage elements from Child Page

I've looked at several examples online and none of then seem to work for me.

All I am trying to do is access the contents of a label from the masterpage header.

Here is what i have..

A Label on the Content Page

<asp:Label ID="StaffUserName" runat="Server" />

A Label on the MasterPage called "ThisLoginName"

    <header>
        <div class="content-wrapper">
            <div class="float-left">
                <p class="site-title">
                    <a runat="server" href="~/">Home</a>
                </p>
            </div>
            <div class="float-right">
            <section id="login">
                Welcome! <b><asp:Label ID="ThisLoginName" runat="server" /></b>

            </section>
            <nav>
                <ul id="menu">
                    <li><a runat="server" href="~/">Home</a></li>
                    <li><a runat="server" href="~/Admin">Admin</a></li>

                </ul>
            </nav>
        </div>
    </div>
</header>

I've read a few tutorials online but i can't seem to work this out. I do however have this at the top of my content page

<%@ MasterType VirtualPath="~/Site.Master" %>

If anyone can help i'd appreciate it.

Upvotes: 0

Views: 2078

Answers (3)

SteveU
SteveU

Reputation: 111

Fixed..

It was down to the fact that my code to pull the username from the windows login was running at Page load in the masterpage.

So i moved it to the

public void master_Page_PreLoad(object sender, EventArgs e)

section and then it worked.

So it must have been working all along but was pulling through an empty field.

Thanks

Upvotes: 1

R.C
R.C

Reputation: 10565

You need to Add Public properties in Master page class:

public string LabelText 
{ 
get { return StaffUserName.Text; } // StaffUserName is the ID of your LABEL
set { StaffUserName.Text = value; } 
} 

Seeing you have added: <%@ MasterType VirtualPath="~/Site.Master" %> , So in your content page access this as:

Master.LabelText = "MyText";

OR

string test= Master.LabelText;

Upvotes: 1

Related Questions