How to Set Master Page dynamically?
void Page_PreInit(Object sender, EventArgs e)
{
this.MasterPageFile = "~/MyMaster.master";
}
Explanation: You can attach a master page dynamically to a content page. Because the master page and content page are merged during the initialization stage of page processing, a master page must be assigned before then. Typically, you assign a master page dynamically during the PreInit stage.
Please note this article on MSDN:
http://msdn.microsoft.com/en-us/library/c8y19k6h.aspx
void Page_PreInit(Object sender, EventArgs e)
{
this.MasterPageFile = "~/NewMaster.master";
}
You can, by setting the MasterPageFile property of the Page. However, this will throw an InvalidOperationException
if it is called after the PreInit event. Have a look at the ASP.NET Page Lifecycle
The MasterPageFile property can be set only in the PreInit event; attempting to set the MasterPageFile property after the PreInit event will throw an InvalidOperationException exception. If the MasterPageFile property is not valid, an exception of type HttpException is thrown later in the page life cycle, but no exception is thrown when the property is set in the PreInit event.