开发者

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 l开发者_Go百科ike 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.


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;
}


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜