Thursday, May 20, 2010

How to add webpart programmatically in SharePoint webpart page

Adding webpart programmatically in SharePoint webpart page

There are two scenarios:
1. you add a web part that is displaying data for a list, which is called List View Webpart. List view webpart will be created automatically when you create a list.

Here is the code to achieve that.

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

2. you add any other web part (e.g. a custom web part or a 3rd party web part like the SmartPart). The




// 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 = @" Left SmartPart, Version=1.0.0.0, Culture=neutral, PublicKeyToken=dd064a5b12b5277a SmartPart.UserControlWebpart ~\UserControls";

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.

No comments: