SearchForKnowledge
SearchForKnowledge

Reputation: 3751

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?

Upvotes: 0

Views: 24

Answers (2)

mason
mason

Reputation: 32728

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();.

Upvotes: 1

dario
dario

Reputation: 5269

You can easily do it like this.

In your Content Page:

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

In your Code Behind:

Master.PopulateMessageSlider();

More information here.

Upvotes: 1

Related Questions