Add web part to sharepoint page using C#

Mostly while working with MOSS 2007 or WSS 3.0 sites we add and remove the web part using the options available in site. To add same web part to multiple site then the task becomes little tedious and time consuming.

In order to get rid of the adding web part from web programmer and site administrator can use this simple codes to make their life more simpler. What I mean is adding web part using code.

Code goes like this

Using Microsoft.Sharepoint;
Using System.Web.UI.WebControls.WebParts;

public static string AddWebPartToPage(SPWeb web, string pageUrl, string webPartName, string zoneID, int zoneIndex)
	using (SPLimitedWebPartManager webPartManager = web.GetLimitedWebPartManager(pageUrl, PersonalizationScope.Shared))
		using (WebPart webPart = CreateWebPart(web, webPartName, webPartManager))
			webPartManager.AddWebPart(webPart, zoneID, zoneIndex);
			return webPart.ID;

public static WebPart CreateWebPart(SPWeb web, string webPartName, SPLimitedWebPartManager webPartManager)
	SPQuery qry = new SPQuery();
	qry.Query = String.Format(CultureInfo.CurrentCulture,
		"<Where><Eq><FieldRef Name='FileLeafRef'/><Value Type='File'>{0}</Value></Eq></Where>",

	SPList webPartGallery = null;

	if (null == web.ParentWeb)
		webPartGallery = web.GetCatalog(SPListTemplateType.WebPartCatalog);
		webPartGallery = web.Site.RootWeb.GetCatalog(SPListTemplateType.WebPartCatalog);

	SPListItemCollection webParts = webPartGallery.GetItems(qry);

	XmlReader xmlReader = new XmlTextReader(webParts[0].File.OpenBinaryStream());
	string errorMsg;
	WebPart webPart = webPartManager.ImportWebPart(xmlReader, out errorMsg);

	return webPart;

There is also other way to perform  the same task, that is using SPWebPartCollection

using (SPSite site = new SPSite(“url of site”)
   using (SPWeb web = site.OpenWeb())
     SPWebPartCollection webPartCol = web.GetWebPartCollection("url of page",Storage.Shared);      

     //create new web part object
     WebPartToBeAdded wpPart = new WebPartToBeAdded();      

     //set properties of new wpPart object
     wpPart.ZoneID = "web part zone id";
     wpPart.Title = "Title for web part";
     wpPart.ChromeState = System.Web.UI.WebControls.WebParts.PartChromeState.Normal;
     wpPart.ChromeType = System.Web.UI.WebControls.WebParts.PartChromeType.None;      

     //add new webpart object to webPartCol collection

     //update web object

Hope this helps

Tagged with: ,
  • Fidus

    Thank you for this article :))
    I’m just wondering about the zoneID and zoneIndex you’re using , what shall i put as string and int when i call the method ??

    thank you

  • Fidus

    I hope that u can communicate us with samples of the urls ur using .. cause i tried to put :
    /_Layouts/MyProject/MyAppPage.aspx , in the url and it doesnt work , i tried to give the whole url too http://mymachine:7777//_Layouts/MyProject/MyAppPage.aspx also it doesnt work .. i dont know how to make this work , so could you help me :)) thank you

  • Alex

    I’m a bit late i guess, but you should use: “Lists/ListName/NewForm.aspx”

  • Mike

    You code has no context! You must be adding these to application pages

  • I am really loving the theme/design of your site.
    Do you ever run into any internet browser compatibility problems?

    A couple of my blog readers have complained about my blog not
    operating correctly in Explorer but looks great in Firefox.

    Do you have any solutions to help fix this problem?

  • What’s Taking place i am new to this, I stumbled upon this I have discovered It
    absolutely useful and it has aided me out loads. I am hoping to contribute
    & help different customers like its aided me. Good job.

  • Howdy! I understand this is somewhat off-topic however I
    needed to ask. Does building a well-established website
    such as yours require a large amount of work?
    I’m completely new to running a blog however I do write in my journal
    daily. I’d like to start a blog so I can share my experience and feelings online.
    Please let me know if you have any kind of suggestions or tips for new aspiring bloggers.


  • My programmer is trying to convince me to move to .net from PHP.

    I have always disliked the idea because of the costs.
    But he’s tryiong none the less. I’ve been using Movable-type
    on a variety of websites for about a year and am nervous about switching to
    another platform. I have heard great things about
    Is there a way I can import all my wordpress content into it?
    Any kind of help would be really appreciated!