Adding web parts programmatically in SharePoint

When I’m delivering a SharePoint developer course I usually challenge my students to think of something that they would like to do in SharePoint with the object model. So far I always have been able to write the code, and today I got another interesting challenge: how can you add a web part to a web part page in code.


The code to accomplish this is quite easy, basically there are two scenarios: you add a web part that is displaying data for a list, or you add any other web part (e.g. a custom web part or a 3rd party web part like the SmartPart). The code for the first scenario is:

using Microsoft.SharePoint;
using Microsoft.SharePoint.WebPartPages;

// Get a reference to a web and a list
SPSite site = new SPSite("http://localhost:8000");
SPWeb web = site.OpenWeb();
SPList list = web.Lists["Contacts"];

// Instantiate the web part
ListViewWebPart wp = new ListViewWebPart();
wp.ZoneID = "Left";
wp.ListName = list.ID.ToString("B").ToUpper();
wp.ViewGuid = list.DefaultView.ID.ToString("B").ToUpper();

// Get the web part collection
SPWebPartCollection coll = 

// Add the web part


First you get a reference to the SPWeb in which you want to add the web part, and to the list you want to use (in this example the Contacts list). Next you create an instance of the ListViewWebPart class, in which you can set the ZoneID, the ListName and the ViewGuid. This is the tricky part, the ListName property should contain the ID of your list (a GUID), not the name of your list!! But the ListName property is of the type string, so you need to convert the List GUID to a string using .ToString(“B”).ToUpper(). The same goes for the ViewGuid. Finally you need to get a reference to the WebPartCollection for the page in which you want to add the web part (in this example the home page, being default.aspx). Now you can add the web part using the Add method.


For the second scenario, the code is as follows:

// Get a reference to a web and a list
SPSite site = new SPSite("http://localhost:8000");
SPWeb web = site.OpenWeb();

// Get the web part collection
SPWebPartCollection coll = 

string dwp = @"<?xml version=""1.0"" encoding=""utf-8""?>
<WebPart xmlns:xsd=""
<Title>SmartPart List</Title> <ZoneID>Left</ZoneID>
<Assembly>SmartPart, Version=, Culture=neutral,
<UserControlPath xmlns=""SmartPart"">
; coll.Add(dwp);

The first section is the same, get a reference to your site and the WebPartCollection (you don’t need a reference to a list). Next you need to build a XML string containing the information about the web part you want to add. The contents of that string are the same as the DWP file that you need to create to use your custom web parts. A trick to figure out what needs to be in there (especially if you want to specify values for some properties) is to put the web part on a page (using the web interface), and choose “Export” from the dropdown menu of the web part. This will save the contents of the DWP in a file. Finally you can add the web part by calling the Add method of the WebPartCollection and using the dwp string as a parameter.


  • Hi Jan,

    Thanks for this blog post... I got this question so often, but never had the time to write it down. Good to have a source to reference now.

  • ohhh :)

    What a good idea to try a new SharePoint Nant task !!!

  • Hi Maurice, thanks for the link! I didn't mention it in my post, but the second question was: what if I want to display the contents of a list. :-)

  • How would you change the parameters in a web part, such as the detail link in the MyAlerts web part, for instance?

  • It's more difficult to add a web part to MySite... The question is, do you know how to do this?

  • 2 follow up questions- Is it possible to add a web part connection using this method? and have you ever needed to set AllowUnsafeUpdates to get this to work?

    good stuff.

  • follow up- I am using this method via the &lt;executeurl&gt; element of the onet file. For some reason the only way it would work was if I specified the following:

    SPWebPartCollection parts = spFile.GetWebPartCollection(Storage.Shared);

    parts.Web.AllowUnsafeUpdates = true;

    System.Guid wpGuid = parts.Add(wp);

    If I cast the ListViewWebPart as a WebPart, I can get at the connection properties. I just need to know how to set them now :)

  • Thanks for the blog. It was what i was looking for. I have one additional Issue. I get the following error when I programmatically try to add a webpart to my webpartpage. Even though my web part is registered as safe within the Web.config.

    "A Web Part or Web Form Control on this Web Part Page cannot be displayed or imported because it is not registered on this site as safe".

    Any Ideas

  • This was very helpful, thanks for the post. One quick issue to note though, I first took the code and dumped it into my SharePoint dev directory that is a managed path where I put all my custom .ASPX files to manipulate SharePoint. The sample code consistently produced the error 'A Web Part or Web Form Control on this Web Part Page cannot be displayed or imported because it is not registered on this site as safe'. I knew the control was safe as it's running on a number of pages already but it took a file to narrow down the problem. I finally realized it might have to do with the Context of the managed path not using the normal web.config of the SharePoint site, moved the code into a console app where the error immediately disappeared. It seems very weird as I would assume the Methods of the GetWebPartCollection operate in the context of the SPSite object, but it doesn't seem so.


  • I get "Cannot connect to the configuration database" when I debug and try to execute this line:
    SPList list = web.Lists["Contacts"];

    I am developing on the server as an administrator of the server. I have the trust level set to 'Full'. I have tried impersonating another local administrator using the WindowIdentity via LogonUser in the advapi32.dll, etc.

    What am I missing? Thanks in advance for your help!

  • I forgot to mention... my code runs on a different port than SharePoint and uses a different application pool.

  • This is very helpful. I tried this in a toolpart to add a new webpart in the current page. It works fine but there is one issue there.

    When I add my webpart properties and clicked the OK button on the toolpart, when the page first reloaded, the added webpart is not shown. I can only see the one I added earlier.


  • How do you add context menus programmatically?

  • Can anyone help me in creating a form library programmatically.
    I dont want to create it from the site. I want to create it programmatically.


  • Has anyone tried using this against a view that isn't default? Everything I've tried with this code binds the view to the default, even though I pass in the guid for the view I want, this is what Im currently doing...

    SPList list = web.Lists[listName];
    SPView view = list.Views[viewName];

    listView.ListName = list.ID.ToString("B").ToUpper();
    listView.ViewGuid = view.ID.ToString("B").ToUpper();
    Guid lvwpguid = webParts.Add(listView);

    Any Ideas what I need to do to get the list view Web part to display the view I want and not the default view?

  • Is it possible to have Custom WebPartManager in Sharepoint

    if so can i put my custom WebPartManager in the Custom Master Page.

    Please hlep me


  • I have a web app that tries to do precisely the same thing with pretty much the same code base. However, on execution I get the following error:

    "This page has encountered a critical error. Contact your system administrator if this problem persists."

    Has anyone seen this before? Any ideas?

  • I have implmented the custom webpart which delete a perticular webpart if that webpart is there on page.

    The only thing is that I am able to locate that webpart but when i tryt o delete the webpart the webpart give s me error saying,

    The "Class1" Web Part appears to be causing a problem. The operation could not be completed because the Web Part is not on this page.

    The same error is coming when i try to change the title of the webpart.

    Anyone having the idea how to solve it.

  • Hi Jantie

    I am trying to add a custom web part in sharepoint.
    I used the code for the second scenario(adding custom web part). But while reading the xml dwp string (at statement > coll.Add(dwp);)
    it giving a runtime exception.
    the error message : There is an error in XML document (1, 40).

    my dwp string is as follows:
    string dwp = @" SmartPart List Left DisplayTitleOfList, Version=, Culture=neutral DisplayTitleOfList.DisplayTitleWebPart ";

    Please help me Jan.

  • Hi Jan,
    The first scenario code is running beautifully from console application.That is I can add web part programmatically from console application .

    But using wss v3.0 web part ,from web control library project(MS VB2005) the same code is not running.It giving an unexpected error,whenver i want to add the web part (that contain the code for adding another web part) in the web part page.

  • Hey please let me know where to write the code and how to run it ?
    I am new in MOSS 2007 and am unable to figure it out where to write the code.

    Thanks for the help

  • Hi,

    I need help. I have a user control and I need to load it in smart part. I am using an aspx page(Test.aspx) which has a Default.Master (Sharepoint's master page) as master page. I need to add user control as a smart part programmatically on test.aspx. I have taken a webpartzone on my test.aspx page as shown below,

    I need to add smart part in this zone. I have used the second code block (using DWP) for this.

    Here I am getting error as mentioned below,

    An unexpected error has occurred.

    Web Parts Maintenance Page: If you have permission, you can use this page to temporarily close Web Parts or remove personal settings. For more information, contact your site administrator.

    Can you pls hel me in this?

  • This info was damn helpful. Thanks everyone.

  • I have created a site in MOSS 2007 using Colloboration site template. It has a "My Site" feature for personalization. These "My Site" have standard "Getting Started" web part to assist users with the use of SharePoint. The Getting Started web part should be removed automatically from a users "My Site" after two weeks if, it has not been manually removed by the user. Once the user has removed the web part, it can only be added back manually by the user.

    Kindly Request you provide the guidelines, any links, or best practices to
    achieve this functionalities.

Comments have been disabled for this content.