Question

How do I define a label in a masterpage from inside one control page, withouth losing it when I navigate to another control page? I know that I can use this code and it works:

        (Master.FindControl("myControl") as Label).Text = "someNewContent";

But I have to define this on every page to keep the same content in the label. Is there a easier/shorter way to define this piece of code only one time in the whole program? Thanks in advance.

Was it helpful?

Solution

I think I get the gist of what you're asking:

Firstly, I would strongly type the master page, in your content page just below the @Page directive, by using the @MasterType directive:

<%@ MasterType TypeName="*fully qualified type of your master page*" %>

Next, place a public property on your master page, like so:

public string MyText
{
  set { this.ViewState["TheText"]; }
}

In your content page (during the Page_Init, for instance) you can add:

this.Master.MyText = "Whatever you want to say!";

Then load your master pages control text property in the Page_Load event:

protected void Page_Load(object sender, EventArgs e)
{
  this.myControl.Text = Convert.ToString(this.ViewState["TheText"]);
}

This won't persist from content page to content page because each content page instantiates a new instance of the master page. In that case, put whatever text you want to persist in Session, then read it in the mater pages Page_Load event.

Hope this answers your question.

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