The Muffin Man
The Muffin Man

Reputation: 20004

How to set a label control in a master page from a utility class

I have a class named utility in my App_code folder that holds the logic to set a labels text.

public void Mgr_BreadCrumbs(string text)
    {
        Manager.MasterPages.Master master = new Manager.MasterPages.Master();

        Label lblHeader = (Label)master.FindControl("lblHeader");
        lblHeader.Text = text;
    }

And then in each of my pages I was trying to set it like this:

        utility u = new utility();
        u.Mgr_BreadCrumbs("Categories");

I'm getting am object reference not set to an instance of an object on the lblHeader.Text = text; line of code.

Upvotes: 0

Views: 6099

Answers (2)

Four
Four

Reputation: 900

You can use a extention method to simplify you call.

For Example:

public partial class Default : System.Web.UI.Page
{
    public void Page_Load(object sender, EventArgs e){
        Master.SetText("Categories");
    }
}


public static class Helper{

    public static void SetText(this MasterPage master, string text){

        ((Label)((MyMaster)master).FindControl("lblHeader")).Text = text;
    }

}

I'd make "lblHeader" a parameter so you can reuse the method for to assign text to other masterpage controls.

Upvotes: 1

StriplingWarrior
StriplingWarrior

Reputation: 156534

That's because you're creating a new instance of your master page's class, but it's not being initialized, so the label doesn't have a value.

What you really want to do is probably pass either the current Page or its Master Page into the utility method so that it can find the actual Master Page instance being used by the current page. (Setting a label value on some other instance that you create won't have any effect on the current page's state).

u.Mgr_BreadCrumbs((Manager.MasterPages.Master)this.Master, "Categories");

...

public void Mgr_BreadCrumbs(Manager.MasterPages.Master master, string text)
{
    Label lblHeader = (Label)master.FindControl("lblHeader");
    lblHeader.Text = text;
}

Upvotes: 1

Related Questions