3

I have a label named headerLabel in my master page, and I'd like to set its text to the title from the content page. How do I do this?

Phil
  • 563
  • 4
  • 6
  • 16
  • 1
    you can use [this question](http://stackoverflow.com/questions/1092784/how-to-control-elements-on-a-asp-net-master-page-from-child-page) – Amir Jan 16 '14 at 11:20

2 Answers2

5

On your master page create a public property - something along the lines of:

public string LabelValue
{
  get{ return this.headerLabel.Text;}
  set{ this.headerLabel.Text = value;}
}

Then, on your child page you can do this:

((MyMasterPage)this.Master).LabelValue = "SomeValue";
Liath
  • 9,913
  • 9
  • 51
  • 81
  • 2
    You have to provide a public property `headerlabel` which returns this label. Then this approach is better than the [`FindControl` approach](http://stackoverflow.com/a/21160299/284240). Otherwise you cannot access it directly since controls are `protected` by default. – Tim Schmelter Jan 16 '14 at 11:19
  • Nice suggestion - I've updated, I always prefer to access properties - I like the idea of having a public property on the master page rather than the public label. – Liath Jan 16 '14 at 11:22
  • How do I go about adding a public property? My project says the 'MasterPage' does not contain a definition for 'LabelValue' – Phil Jan 16 '14 at 11:31
  • @PhilipLoffler add the first code segment to your master page – Liath Jan 16 '14 at 11:33
  • I have done this but I'm still getting the same issue – Phil Jan 16 '14 at 11:45
  • @PhilipLoffler where have you added it? In the code behind of the master page class? – Liath Jan 16 '14 at 11:47
  • I put it in there and in a script in MasterPage.Master – Phil Jan 16 '14 at 11:50
  • let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/45370/discussion-between-liath-and-philip-loffler) – Liath Jan 16 '14 at 11:51
2

You need to find control by it's id on the content page then set text property of label like this

(Label)MasterPage.FindControl("headerLabel").Text="Your Title";

it better to check null before assigning the text property like this

 Label mylbl= (Label) MasterPage.FindControl("headerLabel");
    if(mylbl!= null)
    {
        mylbl.Text = "Your Title";
    }
Sain Pradeep
  • 3,119
  • 1
  • 22
  • 31
  • Hard coding control names as strings is BAD! – Amir Jan 16 '14 at 11:28
  • @Amir I agree to a point but you have to assume some things are set otherwise you could never redirect or write javascript! – Liath Jan 16 '14 at 11:34
  • 1
    Follow this article. It described all of the way of sending data to master page like itle, Meta Tags, and Other HTML Headers in the master page. https://learn.microsoft.com/en-us/aspnet/web-forms/overview/older-versions-getting-started/master-pages/specifying-the-title-meta-tags-and-other-html-headers-in-the-master-page-cs – Kabir Hossain Sep 13 '17 at 05:49