Home > .net 2.0 > Programmatic setting of the MasterPageFile

Programmatic setting of the MasterPageFile

October 18, 2006

A reader in m.p.dotnet.framework.aspnet asked how to set the MasterPageFile on startup using a PreInit method. This can be done by setting this page-by-page, or more painlessly, creating a base page and having all of the other pages inherit from it.

First, create, or edit, your base page. Typically this page is in your ~/App_Data directory. Here is an example of how to 1) add an EventHandler to call your new PreInit and 2) set the MasterPageFile in the PreInit. For this example, our base page is called BasePage.cs.

public class BasePage : Page
{
public BasePage() : base()
{
  base.PreInit += new EventHandler(Page_PreInit);
}

protected void Page_PreInit(object sender, EventArgs e)
{
  this.MasterPageFile = “~/MasterPage.master”
}
}

Second, on the code-behind files of your individual pages, have them inherit your base page (if you’re not already). In the example below, the Default.aspx page will inherit the BasePage created above.

public partial class _Default : BasePage
{

}

From here, you’re good to go. The new PreInit will fire for each page, and this method allows you to change the location of the MasterPageFile in a single location rather than in each and ever page. In theory, you could also pull this from the web.config using the System.Configuration namespace.

Categories: .net 2.0
%d bloggers like this: