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

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 = "";
ProjectAccountingWebPartMgr.AddWebPart(pvwp, "Body", 0);

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

Salaudeen Rajack - Information Technology Expert with Two-decades of hands-on experience, specializing in SharePoint, PowerShell, Microsoft 365, and related products. He has held various positions including SharePoint Architect, Administrator, Developer and consultant, has helped many organizations to implement and optimize SharePoint solutions. Known for his deep technical expertise, He's passionate about sharing the knowledge and insights to help others, through the real-world articles!

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

  • Can this be done with PowerShell?

    • This is the real question 🙂

  • 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

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

  • 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.

    • 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.

  • 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!

  • 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?

    • 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.


Leave a Reply

Your email address will not be published. Required fields are marked *