Monday, 24 February 2014

Removing a web part

Following code snippet can be used to remove a web part from an existing SharePoint website:
  1.  using (SPSite spSiteTest = new SPSite(“SiteURL”) 
  2.  {
  3.    using (SPWeb spWebTest = spSiteTest.OpenWeb())
  4.    {
  5.      SPWebPartCollection webparts = spWebTest.GetWebPartCollection("WebPageURL", Storage.Shared);
  6.      for (int k = 0; k < webparts.Count; k++)
  7.      {
  8.        //get reference to webpart
  9.        Microsoft.SharePoint.WebPartPages.WebPart wp = webparts[k];

  10.        //check webpart Title to find webpart which is to be removed
  11.        if (wp.Title == "WebPartName")
  12.        {
  13.          //delete webpart
  14.          webparts.Delete(wp.StorageKey);

  15.          //update spWeb object
  16.          spWebTest.Update();  
  17.       }                                                                                                                                                            }
  18.    }
  19.  } 

No comments:

Post a comment