Cunners
Cunners

Reputation: 1286

Can I change the text of a label in a masterpage when loading a content page?

I have a label in a master page (sample.master) called lblHeading.

I want to dynamically change the text of the label when I load the content page.

I need to do this because I want to change the heading to something meaningful but only after I know about the content of the page.

Is this possible?

Upvotes: 9

Views: 29867

Answers (6)

Fandango68
Fandango68

Reputation: 4868

It also depends on how deep your controls inside the Master page are. In my case, I had a Label control inside a ContentPlaceHolder control... so I had to do this...

Label myLBL = this.Master.FindControl("HeaderContent").FindControl("myLabel") as Label; 

Upvotes: 0

Gary Huckabone
Gary Huckabone

Reputation: 412

Do as stated above. Then, e.g., from your page do this (master page has label with ID="Label_welcome"):

Label mpLabel = (Label)Page.Master.FindControl("Label_welcome");

  if (mpLabel != null)
  {
    mpLabel.Text = "Welcome Fazio!";
  }

Upvotes: 3

Adrian Godong
Adrian Godong

Reputation: 8921

Yes, it is possible. MasterPage behaves just like UserControl in your page.

Possible steps to implement this:

  1. Create a property or method on the MasterPage that enables you to make changes to the Label. E.g.:

    public void ChangeLabel(string label) {
      lblHeading.Text = label;
    }
    
  2. From your Page, get the reference to the MasterPage by using the Page.Master property.

  3. Call the method defined in step 1 to change the MasterPage contents.

Additional info: You may need to cast Page.Master into your MasterPage type, try Coding the Wheel's link for instructions on how to do that.

Upvotes: 3

Muhammad Akhtar
Muhammad Akhtar

Reputation: 52241

yes, you can in this very simple way........

((Label)Master.FindControl("lblHeading")).Text = "your new text";

Upvotes: 16

CD..
CD..

Reputation: 74146

You can create a public property in the masterpage that will change the label.

public string Heading
{
    set 
    {
        lblHeading.text = value;
    }

}

Upvotes: 2

user2189331
user2189331

Reputation:

Yes.

You want to create a strongly-type master page and you can then access it's properties from your content page during Page_Load or wherever else.

Upvotes: 6

Related Questions