Wednesday, May 9, 2012

Change page layout programmatically SharePoint 2010

In this article we will discuss how to change page layout programmatically in SharePoint 2010. You can also check an article on how to Create Page Layout using SharePoint Designer 2010.

Here we will discuss how to change the page layout at the time of site creation. So for this we have written one event receiver. You can see an article on how to create event receiver using Visual Studio 2010 in SharePoint 2010.

Since we want to change the layout after the site creation, so we need to write our code in the WebProvisioned event as shown below.

public override void WebProvisioned(SPWebEventProperties properties)
        {          
            try
            {
                if (PublishingWeb.IsPublishingWeb(properties.Web))
                {
                    PublishingWeb curPubWeb = PublishingWeb.GetPublishingWeb(properties.Web);

                    foreach (PageLayout curLayout in curPubWeb.GetAvailablePageLayouts())
                    {
                        if (curLayout.Name == "OurCustomPageLayOutName.aspx")
                        {
                            foreach (PublishingPage curPage in curPubWeb.GetPublishingPages())
                            {
                                curPage.CheckOut();
                                curPage.Layout = curLayout;
                                curPage.Update();
                                curPage.CheckIn("");
                            }
                            break;
                        }

                    }
                }
            }
            catch (Exception ex)
            {
                throw;
            }
}

Once you will deploy the event receiver, try creating a web site and you will see the layout must be changed to OurCustomPageLayOutName.aspx layout.

No comments:

Post a Comment