Monday, November 5, 2012

SharePoint2010: Programatically Delete Webpart From Gallery

Scenario: Programmatically deleting a webpart from webpart gallery

Solution: Add a feature receiver to the webpart feature and paste below code in featuredeactivating

SPSite site = properties.Feature.Parent as SPSite;

List<int> wpToDelete = new List<int>();

SPList wplist = site.GetCatalog(SPListTemplateType.WebPartCatalog);

foreach (SPListItem item in wplist.Items)
{

  
    if (item.DisplayName.ToLower().Contains("webpartname"))
    {
      wpToDelete.Add(item.ID);
    }

}

foreach(int wpID in wpToDelete)
{
 
  SPListItem wpitem = wplist.GetItemById(wpID);

  wpitem.Delete();
}
 
wplist.Update();
}