Friday, September 21, 2012

Change master page programmatically SharePoint 2010

In this article we will discuss how to change master page programmatically in  SharePoint 2010. You can also check my last article on how to change page layout programmatically here. You can check how to create custom master page using SharePoint 2010 designer in SharePoint 2010

We will discuss how to change the master page at the time of site creation. So for that purpose we will have to write one event handler that will fire in the  WebProvisioned event. You can check an article on how to create event receiver using Visual Studio 2010 in SharePoint 2010

Once we created the event receiver we need to override the WebProvisioned() method as below to change the master page.

public override void WebProvisioned(SPWebEventProperties properties)
                using (SPWeb currentWeb = properties.Web)
                    currentWeb.AllowUnsafeUpdates = true;
                    currentWeb.MasterUrl = "/_catalogs/masterpage/MyCustomMaster.master";
                    currentWeb.CustomMasterUrl = "/_catalogs/masterpage/MyCustomMaster.master";
//You can use the below approach also, but sometimes that did not work.
                    //currentWeb.CustomMasterUrl = currentWeb.Site.RootWeb.ServerRelativeUrl + "/_catalogs/masterpage/MyHpIndigo2ndLevelMaster.master";
                    currentWeb.AllowUnsafeUpdates = false;
            catch (Exception ex)

Once you will deploy the event receiver, try creating a web site and you will see the default master page will change to the custom master page.
Mobile Solutions by KWizCom

No comments:

Post a Comment