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;
}

Salaudeen Rajack

Information Technology Professional with Two decades of SharePoint Experience.

9 thoughts on “How to Add Web Parts to the Page Programmatically?

  • August 13, 2020 at 2:17 PM

    Can this be done with PowerShell?

    Reply
    • September 15, 2020 at 8:51 PM

      This is the real question 🙂

      Reply
  • November 9, 2017 at 2:48 PM

    Hi this is really nice article ,I have implemented in my code .
    but I wanted to multiple webparts in Top,Left,Right zones.
    how can I add ,please share code if you have ,it will be very helpful
    thanks

    Reply
  • October 31, 2017 at 3:35 PM

    add date filter web part to a web page in sharepoint by SSOM c#

    Reply
  • April 24, 2015 at 12:10 PM

    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.

    Reply
    • March 9, 2017 at 3:13 PM

      Create another feature then create an event receiver in that feature and add the code there. In your package file in Visual Studio make sure that the feature you just created is at the bottom of the list, or at least after the web part is added.

      Reply
  • August 21, 2013 at 5:54 PM

    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!

    Reply
  • January 8, 2013 at 4:43 AM

    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?

    Reply
    • April 1, 2013 at 9:39 AM

      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.

      Reply

Leave a Reply