How to use event handler to add web part to web part page

When you are designing a new page layout and want to have default web parts to be included when user creates a new page off this page layout. You can accomplish this by several ways.

1.       Easiest way probably is to put web parts inside the page layout. – But you cannot change the web part settings without modifying page layout.

2.       Use <AllUsersWebPart/> within element manifest file where you provisioning the page layout. – It is good way to do it only if it can work properly. I am having issues with this method. Having Default Web Parts in new Pages Based Off Page Layouts in MOSS 2007 Publishing Sites have great post about how to do this.

Or you can use event handler to add default web parts to the page when page gets created and added to page library.

First step, create a page layout with empty WebPartZone.


<!-- page layout .aspx -->

<WebPartPages:WebPartZone id="DefaultWebPartZone" runat="server" title="Feature Zone">


Second step, create a list event handler and register it with “Page document library”

<!-- Feature element manifest .xml-->

<Elements xmlns="http://schemas.microsoft.com/sharepoint/">

  <Receivers ListTemplateId="850">





      <Assembly>YourAssemblyNameHere, Version=, Culture=neutral, PublicKeyToken=0123456789ABCDEF</Assembly>







Thrid step, write your code to insert the web part to page.

public class WebPartPageBuilder : SPItemEventReceiver
        public override void ItemAdded(SPItemEventProperties properties)
            //we check if event fired from page library and page was created base on correct page layout (with web part zone).
            if (properties.ListTitle.Equals("Pages") && properties.ListItem.ContentType.Name.Equals("Page Layout Name")) 
                SPFile thisFile = properties.ListItem.File;
                SPLimitedWebPartManager webPartManager = thisFile.GetLimitedWebPartManager(PersonalizationScope.Shared);
                ContentByQueryWebPart defaultCQWPWebPart = new ContentByQueryWebPart();
                /**web part settings ommited here**/ 
                webPartManager.AddWebPart(defaultCQWPWebPart, "DefaultWebPartZone", 1);

 Now, you have created a event handler that inserts web part to the page.

blog comments powered by Disqus