Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to programmatically update content in a SharePoint Web Part?

Does anybody know how to programmatically update the content of any of the standard SharePoint v3 Web Parts?

As an example, put a Link Summary Web Part on a page. Add some links to it. Now, how can I update this information using the WSS API? I have not found any direct way to do this, my only idea so far is to export the Web Part, (then delete it), modify the generated XML, and import it back. But surely, there must be an easier way?

like image 723
Magnus Johansson Avatar asked Jan 27 '09 22:01

Magnus Johansson


1 Answers

You can use the SPLimitedWebPartManager class to manipulate Web parts on a Web part page. An instance of this class can be obtained from an SPFile object as follows:

using (SPSite site = new SPSite("<site url>"))  // e.g. http://server/sites/asite
using (SPWeb web = site.OpenWeb())
{
    SPFile file = web.GetFile("<page url>");   // e.g. /sites/asite/default.aspx
    SPLimitedWebPartManager lwpm = file.GetLimitedWebPartManager();
    SPLimitedWebPartCollection webParts = lwpm.WebParts;
    WebPart wp = webParts[<id, index or Guid>];

    // Add your code to update the Web Part

    lwpm.SaveChanges(wp);
}

You can also add or delete web parts with the SPLimitedWebPartManager.

like image 145
Lars Fastrup Avatar answered Sep 22 '22 09:09

Lars Fastrup