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