Saturday, August 4, 2012

How to Add Web Parts to the Page Programmatically

Requirement is to add OOTB and Custom web parts to a web part page programmatically via features. I'm sharing the code snippets:

To Add Out Of The Box Web Parts: (E.g. Content Query Web Part, Content Editor, Page Viewer Web Part, etc):
      
                SPWeb web = properties.Feature.Parent as SPWeb;   
                //Create the SPLimitedWebPart Manager to Add web parts
                SPLimitedWebPartManager WebPartMgr = web.GetLimitedWebPartManager("Home.aspx", PersonalizationScope.Shared);
               
                //Add Project Matter Title CEWP
                ContentEditorWebPart ProjectDetailsTitleCEWP = new ContentEditorWebPart();

                //Set the Properties of the CEWP
                ProjectDetailsTitleCEWP.Title = "Project Matters Title";
                ProjectDetailsTitleCEWP.ChromeType = PartChromeType.None;

                //Create an XmlElement to hold the value of the Content property.
                XmlElement ProjectDetailsTitle = new XmlDocument().CreateElement("content");
                ProjectDetailsTitle.InnerText = "<img style='BORDER: 0px' src='/_layouts/images/crescent/Project-details.jpg' align='middle'><span style='color: black; font-size: medium; vertical-align: middle'>Project</span><span style='COLOR: #971a1e; font-size: medium; vertical-align: middle'>Details</span><hr style='color: navy;' size='1' />";
                ProjectDetailsTitleCEWP.Content = ProjectDetailsTitle;

                //Add the CEWP to BODY zone
                WebPartMgr.AddWebPart(ProjectDetailsTitleCEWP, "Body", 1);
                WebPartMgr.SaveChanges(ProjectDetailsTitleCEWP);

Add Page Viewer web part
      
                 PageViewerWebPart pvwp = new PageViewerWebPart(); 
                 pvwp.Title = "Project Accounting";
                 pvwp.ChromeType = PartChromeType.None;
                 pvwp.ID = "PageViewer";
                 pvwp.Height = "600px";
                 pvwp.ContentLink = "http://www.Crescent.com/Projects.com";
                 ProjectAccountingWebPartMgr.AddWebPart(pvwp, "Body", 0);
                 ProjectAccountingWebPartMgr.SaveChanges(pvwp);

Programmatically add ListView webpart from: "Project Documents" library
              
                //Get the object of the list of which we are creatin the list viewer webpart
                SPList ProjectDocList = web.Lists["Project Documents"];
                ListViewWebPart oProjectDocsListViewWP = new ListViewWebPart();
                //Set the properties of the webpart
                oProjectDocsListViewWP.ChromeType = PartChromeType.None;
                oProjectDocsListViewWP.Title = "Project Documents";
                oProjectDocsListViewWP.ListName = ProjectDocList.ID.ToString("B").ToUpper();
                oProjectDocsListViewWP.ViewGuid = ProjectDocList.DefaultView.ID.ToString("B").ToUpper();
 
                //Define the zone in which webparts need to be added
                WebPartMgr.AddWebPart(oProjectDocsListViewWP, "Left", 3);
 


Add custom web part programmatically:
In order to add custom web parts, we need to get the web parts from web part gallery first. Here is the helper method:

     //Method to Get the custom web part
        public static System.Web.UI.WebControls.WebParts.WebPart GetWebPart(SPWeb web, string webPartName)
        {
            var query = new SPQuery();
            query.Query = String.Format(
                "<Where><Eq><FieldRef Name='FileLeafRef'/><Value Type='File'>{0}</Value></Eq></Where>",
                webPartName);

            SPList webPartGallery;
            if (web.IsRootWeb)
            {
                webPartGallery = web.GetCatalog(
                   SPListTemplateType.WebPartCatalog);
            }
            else
            {
                webPartGallery = web.ParentWeb.GetCatalog(
                   SPListTemplateType.WebPartCatalog);
            }
            var webParts = webPartGallery.GetItems(query);
            var typeName = webParts[0].GetFormattedValue("WebPartTypeName");
            var assemblyName = webParts[0].GetFormattedValue("WebPartAssembly");
            var webPartHandle = Activator.CreateInstance(
                assemblyName, typeName);

            System.Web.UI.WebControls.WebParts.WebPart webPart =
                (System.Web.UI.WebControls.WebParts.WebPart)webPartHandle.Unwrap();
            return webPart;
        }

Here is how we can add Custom Web Parts to a page:
   //Add "Project Search" Custom web part
                  SPWeb web = properties.Feature.Parent as SPWeb;   

  //Create the SPLimitedWebPart Manager to Add web parts
                SPLimitedWebPartManager WebPartMgr = web.GetLimitedWebPartManager("Home.aspx", PersonalizationScope.Shared);

  //Get the Web Part from Web Part Gallery
                using (System.Web.UI.WebControls.WebParts.WebPart ProjectSearchWp = GetWebPart(web, "ProjectSearch.webpart"))
                {
      //Set the web part Properties
                    ProjectSearchWp.ChromeType = PartChromeType.None;
                    ProjectSearchWp.Title = "Project Search Web Part";
      //Add the web part to Left zone 
                    WebPartMgr.AddWebPart(ProjectSearchWp, "Left", 1);
                    WebPartMgr.SaveChanges(ProjectSearchWp);
                }  



You might also like:
SharePoint Usage Reports
Usage reports, collaboration and audit for SharePoint.
Document SharePoint Farm
Automatically generate SharePoint documentation.
*Sponsored


Check out these SharePoint products:

4 comments :

  1. I am trying to add a custom web part within a web part programmatically. I used the "GetWebPart()" method you provided to get the web part I wanted and added it to a div within my webpart. It worked fine. But I am unable to edit the properties of the inner webpart which I added programmatically. Any idea on how to achieve this?

    ReplyDelete
    Replies
    1. The web part properties are settable only after the web part is added to the page (After web part manager saves the changes)! Once its done, Properties can be set and the SaveChanges method has to be invoked again on the web part manager.

      Delete
  2. Hi,

    Do you know, if it's possible to change the font size of Web Part Page Viewer at SP 2010?
    Or how to change the size percentage of a Web Part?

    Thanks in advance!

    ReplyDelete
  3. Hi i am trying to add a custom web part in a site pages but i am getting the "Error occurred in deployment step 'Activate Features': Object reference not set to an instance of an object." error. I added the code in the Feature activated event. can you please suggest me ... Thanks in advance.

    ReplyDelete

Please Login and comment to get your questions answered!

You might also like:

Related Posts Plugin for WordPress, Blogger...