2

I am using SharePiont Server 2007 Enterprise with Windows Server 2008 Enterprise, and I am using publishing portal template. I am developing using VSTS 2008 + C# + .Net 3.5. I want to know how to add a WebPart to all pages of a SharePoint Site? Any reference samples?

I want to use this WebPart to display some common information (but the information may change dynamically, and it is why I choose a WebPart) on all pages.

jessehouwing
  • 106,458
  • 22
  • 256
  • 341
George2
  • 44,761
  • 110
  • 317
  • 455

2 Answers2

3

There are two ways to do this depending on your situation.

If the sites exist already, you need to iterate over the sites, adding the web part:

http://blogs.msdn.com/tconte/archive/2007/01/18/programmatically-adding-web-parts-to-a-page.aspx

If the sites do not exist then you can add the web part to the site template:

How to add a web part page to a site definition?

Community
  • 1
  • 1
Shiraz Bhaiji
  • 64,065
  • 34
  • 143
  • 252
  • I need to add WebPart to an existing site. I read the code of the first post. It mentions how to add a document library web part, but how to add a custom developed web part? – George2 Dec 06 '09 at 12:14
2

Here's the code from Shiraz's first link worked out a bit more:

(Note: This code is not optimized, for instance, looping through a List's Items collection is not something you should normally do, but seeing as this is probably a one time action there's no problem)

private void AddCustomWebPartToAllPages()
{
  using(SPSite site = new SPSite("http://sharepoint"))
  {
    GetWebsRecursively(site.OpenWeb());
  }
}

private void GetWebsRecursively(SPWeb web)
{
  //loop through all pages in the SPWeb's Pages library
  foreach(var item in web.Lists["Pages"].Items)
  {
    SPFile f = item.File;
    SPLimitedWebPartManager wpm = f.GetLimitedWebPartManager(PersonalizationScope.Shared);

    //ADD YOUR WEBPART
    YourCustomWebPart wp = new YourCustomWebPart();
    wp.YourCustomWebPartProperty = propertyValue;
    wpm.AddWebPart(wp, "ZONEID", 1);
    f.Publish("Added Web Part");
    f.Approve("Web Part addition approved");
  }
  // now do this recursively
  foreach(var subWeb in web.Webs)
  {
    GetWebsRecursively(subWeb);
  }
  web.Dispose();
}
Colin
  • 10,630
  • 28
  • 36