Goal
To remove webparts from a page programmatically using C#.
Code
/// <summary>
/// This function will remove web parts with title passed
/// </summary>
/// <param name="_web">Web object</param>
/// <param name="_pageUrl">The url of the page on which the web part exists.</param>
/// <param name="_title">The title of the Web part</param>
private void RemoveWebPart(SPWeb _web, string _pageUrl, string _webPartTitle)
{
//Remove the control once the page is copied
Microsoft.SharePoint.WebPartPages.SPLimitedWebPartManager _webPartCollection = _web.GetLimitedWebPartManager(_pageUrl, System.Web.UI.WebControls.WebParts.PersonalizationScope.Shared);
//Retrive the webpart and remove
IList<Microsoft.SharePoint.WebPartPages.WebPart> _listFormWebParts = (from _wp in _webPartCollection.WebParts.Cast<Microsoft.SharePoint.WebPartPages.WebPart>()
where string.Compare( _wp.Title , _webPartTitle , true ) == 0
select _wp).ToList();
//Check if there are any web parts found
if (_listFormWebParts != null)
{
foreach (Microsoft.SharePoint.WebPartPages.WebPart _listFormWebPart in _listFormWebParts)
{
//Remove the webpart
_webPartCollection.DeleteWebPart(_listFormWebPart);
//Update
_web.Update();
}
}
}
Tip
Suppose we dont want to remove the webpart using "Title" we want to remove the webpart with type.
//Retrive the webpart and remove
IList<Microsoft.SharePoint.WebPartPages.WebPart> _listFormWebParts = (from _wp in _webPartCollection.WebParts.Cast<Microsoft.SharePoint.WebPartPages.WebPart>()
where _wp.GetType() == typeof(Microsoft.SharePoint.WebPartPages.ListFormWebPart)
select _wp).ToList();