views:

334

answers:

2

Hello everyone,

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.

thanks in advance, George

+1  A: 

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:

http://stackoverflow.com/questions/234302/how-to-add-a-web-part-page-to-a-site-definition

Shiraz Bhaiji
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
Thanks! Question answered!
George2
+2  A: 

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
Cool, thanks man!
George2