Wednesday, June 22, 2005 4:00 PM Jan Tielens

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 = 
	web.GetWebPartCollection("default.aspx", 
	Storage.Shared);

// Add the web part
coll.Add(wp); 

  

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 = 
	web.GetWebPartCollection("default.aspx", 
	Storage.Shared);

string dwp = @"<?xml version=""1.0"" encoding=""utf-8""?>
<WebPart xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns=""http://schemas.microsoft.com/WebPart/v2"">
<Title>SmartPart List 1.0.0.0</Title> <ZoneID>Left</ZoneID>
<Assembly>SmartPart, Version=1.0.0.0, Culture=neutral,
PublicKeyToken=dd064a5b12b5277a</Assembly>
<TypeName>SmartPart.UserControlWebpart</TypeName>
<UserControlPath xmlns=""SmartPart"">
~\UserControls</UserControlPath></WebPart>"
; 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.

Filed under:

Comments

# re: Adding web parts programmatically in SharePoint

Wednesday, June 22, 2005 10:18 AM by Serge van den Oever [Macaw]

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.

# re: Adding web parts programmatically in SharePoint

Wednesday, June 22, 2005 10:28 AM by Renaud Comte

ohhh :)
What a good idea to try a new SharePoint Nant task !!!

# re: Adding web parts programmatically in SharePoint

Thursday, June 23, 2005 2:02 AM by Maurice

Your students should have been able to find the following post using any ol' search engine... :)

http://www.bluedoglimited.com/SharePointThoughts/ViewPost.aspx?ID=70

It's an easy question -- make them dig harder!

# re: Adding web parts programmatically in SharePoint

Thursday, June 23, 2005 2:08 AM by Jan Tielens

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. :-)

# re: Adding web parts programmatically in SharePoint

Monday, June 27, 2005 5:14 PM by John

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

# re: Adding web parts programmatically in SharePoint

Wednesday, June 29, 2005 2:38 AM by Sven Kohler

Thanks for that article.

An other question : Is there way to order webpart in a zone programatically (IE moving bottom webpart to the top) ? Does the order when I add webpart in my code have any influence? Thanks.

# re: Adding web parts programmatically in SharePoint

Friday, July 01, 2005 3:15 AM by Flang

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

# re: Adding web parts programmatically in SharePoint

Wednesday, July 13, 2005 10:40 AM by Chris Bermingham

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.

# re: Adding web parts programmatically in SharePoint

Wednesday, July 13, 2005 11:38 AM by Chris Bermingham

follow up- I am using this method via the <executeurl> 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 :)

# re: Adding web parts programmatically in SharePoint

Wednesday, June 07, 2006 12:19 PM by Janak Shastri

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

# re: Adding web parts programmatically in SharePoint

Sunday, June 18, 2006 4:59 PM by John Lewin

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.

John

# re: Adding web parts programmatically in SharePoint

Thursday, June 22, 2006 3:53 PM by Sandy Brown

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!

# re: Adding web parts programmatically in SharePoint

Thursday, June 22, 2006 4:06 PM by Sandy Brown

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

# re: Adding web parts programmatically in SharePoint

Saturday, July 22, 2006 6:02 AM by David

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.

Thanks!

# re: Adding web parts programmatically in SharePoint

Tuesday, October 03, 2006 3:22 PM by AJ

I get the following error when I try to add the web part anywhere except home page.

List does not exist The page you selected contains a list that does not exist. It may have been deleted by another user. Click "Home" at the top of the page to return to your Web site.

I have changed the URL to the site I am trying to add it to.

SPSite site = new SPSite("http://localhost/sites/test");

SPWeb web = site.OpenWeb();

SPList list = web.Lists["linksList"];

ListViewWebPart wp = new ListViewWebPart();

wp.ZoneID = "TopZone";

wp.ListName = list.ID.ToString("B").ToUpper();

wp.ViewGuid = list.Views[0].ID.ToString("B").ToUpper();

SPWebPartCollection coll = web.GetWebPartCollection ("default.aspx", Storage.Shared);

coll.Web.AllowUnsafeUpdates = true;

coll.Add(wp);

Thanks

AJ

# re: Adding web parts programmatically in SharePoint

Tuesday, November 28, 2006 9:02 AM by Prasath

How do you add context menus programmatically?

# re: Adding web parts programmatically in SharePoint

Tuesday, March 06, 2007 8:39 AM by Prashant Gupta

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.

Thanks

# re: Adding web parts programmatically in SharePoint

Thursday, March 08, 2007 11:33 AM by Ryan

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?

# re: Adding web parts programmatically in SharePoint

Wednesday, April 04, 2007 8:48 AM by Name

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

thanks

Anil

# re: Adding web parts programmatically in SharePoint

Thursday, April 05, 2007 8:22 AM by Praveen Reddy

Good article!!

I implemented this using a console application and was getting 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."

Upon some trouble shooting I found the below article in MSDN. This precisely addresses the above issue.

http://support.microsoft.com/kb/555292

# re: Adding web parts programmatically in SharePoint

Sunday, April 22, 2007 11:38 AM by Britneytwcpd

<a href= http://www.angelfire.com/punk/momede >a map of california</a> <a href= http://www.angelfire.com/indie/gatefu >a housing development</a> <a href= http://www.angelfire.com/punk/kexuxe >a mouthful of sky</a> <a href= http://www.angelfire.com/hiphop/xoviqi >a/c system</a> <a href= http://www.angelfire.com/droid/musosu >a logical approach to discrete math solutions</a>

# re: Adding web parts programmatically in SharePoint

Sunday, April 22, 2007 4:31 PM by Britneyltrar

<a href= http://www.angelfire.com/funky/lebymi >a message to the feds</a> <a href= http://www.angelfire.com/poetry/honyhi >aac lossless encoder</a> <a href= http://www.angelfire.com/hiphop/dovele >a56 cingular free ringtone siemens</a> <a href= http://www.angelfire.com/hiphop/rugoko >aashto bridge design specifications</a> <a href= http://www.angelfire.com/droid/mudyqe >a380 engine test</a>

# re: Adding web parts programmatically in SharePoint

Saturday, April 28, 2007 7:16 AM by Britneydjqzj

<a href= http://www.angelfire.com/indie/gytuxi >a bunny hop on a mountain bike</a> <a href= http://www.angelfire.com/blog/xaregu >a place prepared for you</a> <a href= http://www.angelfire.com/crazy/mojilo >a moment of silence papoose</a> <a href= http://www.angelfire.com/hiphop/wujuha >a reminiscent drive ambrosia</a> <a href= http://www.angelfire.com/crazy/geqedo >a3 freunde</a>

# re: Adding web parts programmatically in SharePoint

Thursday, May 03, 2007 5:40 AM by raz

HI Jan ,

I am working on WSS 3.0 RTM

I have a usercontrol I need to dynamically or programatically add it to a webpage.

As suggested by U

SPWebPartCollection coll

IN WSS 3.0 SPWebPartCollection  has been deprecated

So I used  SPLimitedWebPartManager coll

with this the Addwebpart function doesnot accept a string whereas in the above code U have specified the dwp as a string.

Please help!!!!!

# re: Adding web parts programmatically in SharePoint

Tuesday, May 08, 2007 8:17 PM by gonzolder

ja krevetko! Vsem sasat'!

# re: Adding web parts programmatically in SharePoint

Saturday, May 12, 2007 9:55 AM by Britneyvqlwm

<a href= http://zapafe.front.ru >aaron watson off the record lyrics</a> <a href= http://hodyza.front.ru >a wrinkle in time chapter questions</a> <a href= http://lekylo.front.ru >aarp org game</a> <a href= http://pekelu.front.ru >a heartbreaking work of staggering genious</a> <a href= http://nitovi.front.ru >a guide to latex kopka</a>

# re: Adding web parts programmatically in SharePoint

Saturday, May 12, 2007 9:55 AM by Britneyvqlwm

<a href= http://zapafe.front.ru >aaron watson off the record lyrics</a> <a href= http://hodyza.front.ru >a wrinkle in time chapter questions</a> <a href= http://lekylo.front.ru >aarp org game</a> <a href= http://pekelu.front.ru >a heartbreaking work of staggering genious</a> <a href= http://nitovi.front.ru >a guide to latex kopka</a>

# re: Adding web parts programmatically in SharePoint

Saturday, May 12, 2007 9:55 AM by Britneyvqlwm

<a href= http://zapafe.front.ru >aaron watson off the record lyrics</a> <a href= http://hodyza.front.ru >a wrinkle in time chapter questions</a> <a href= http://lekylo.front.ru >aarp org game</a> <a href= http://pekelu.front.ru >a heartbreaking work of staggering genious</a> <a href= http://nitovi.front.ru >a guide to latex kopka</a>

# re: Adding web parts programmatically in SharePoint

Saturday, May 12, 2007 9:55 AM by Britneymlncz

<a href= http://mijuqe.front.ru >a920</a> <a href= http://kupyty.front.ru >a famosa porta de santiago</a> <a href= http://qycyli.front.ru >a map of canadas provinces</a> <a href= http://tewoze.front.ru >a1h</a> <a href= http://gulopo.front.ru >aankomst zaventem</a>

# re: Adding web parts programmatically in SharePoint

Thursday, May 31, 2007 6:23 PM by jayajit

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?

# re: Adding web parts programmatically in SharePoint

Thursday, June 07, 2007 7:00 AM by sandeep

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.

# re: Adding web parts programmatically in SharePoint

Monday, June 18, 2007 9:44 AM by Kartick Dhara

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.

# re: Adding web parts programmatically in SharePoint

Sunday, August 05, 2007 1:23 AM by Triska

# re: Adding web parts programmatically in SharePoint

Thursday, October 11, 2007 3:54 AM by Misha

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

# re: Adding web parts programmatically in SharePoint

Wednesday, October 24, 2007 1:51 AM by deepali

Hi Jan,

I need to create a report explorer and the report viewer web part programmatically(in MOSS 2007) on the click of a button.

Coding for the web part can be done in the button click event but I am unable  to create the report explorer and report viewer web part through code.

I am relatively new to MOSS. I am trying to write the code  in a web part itself. Should i write it in a console application?

Help of any kind will be appreciated.

thanks

deepali

(maildeepali1@gmail.com)

# re: Adding web parts programmatically in SharePoint

Wednesday, October 24, 2007 6:05 AM by Chirag Darji

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,

<asp:WebPartZone ID="WebPartZone4" Runat="Server"></asp:WebPartZone>

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?

# re: Adding web parts programmatically in SharePoint

Thursday, December 27, 2007 11:10 PM by Bivendra

This info was damn helpful. Thanks everyone.

# re: Adding web parts programmatically in SharePoint

Wednesday, January 16, 2008 10:11 AM by Nagendra

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.