开发者

how to add a WebPart to all pages in a SharePoint site?

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 t开发者_运维技巧o 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.


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?


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();
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜