简体   繁体   中英

How to access masterpage function from within content page

I have the following function in my master page (tried to follow this link: http://www.braintrove.com/id/17/page/3 ):

public void PopulateMessageSlider()
{
    strSql = @"";
    using (SqlConnection conn = new SqlConnection(str))
    {
        //function
    }
}

I am trying to access the function from my content page like this:

Site stMaster;
stMaster = (Site)Page.Master.Master;
stMaster.PopulateMessageSlider();

I am getting the following error:

Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.
[NullReferenceException: Object reference not set to an instance of an object.]
MyProject.Pages.ContentPage1.Page_Load(Object sender, EventArgs e) +279
System.Web.UI.Control.LoadRecursive() +70
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +3177

How can I resolve the issue?

Change stMaster = (Site)Page.Master.Master; to stMaster = (Site)Master; . You don't have a nested master page, so no need to access the master of the master.

Additionally, if the master page type isn't going to change at runtime, you can set the MasterType on your page. That avoids the need for a cast and you can simply do Master.PopulateMessageSlider(); .

You can easily do it like this.

In your Content Page:

<%@ MasterType virtualpath="~/YourMasterPage.master" %>

In your Code Behind:

Master.PopulateMessageSlider();

More information here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM