Wednesday, February 13, 2013

Delete webpart using client object model in SharePoint 2010

In this post we will discuss about how to delete a web part using SharePoint 2010 client object model.

You can also check my previous posts on Document Sets in SharePoint 2010, Add safe controls programmatically in SharePoint 2010 and Developer Dashboard in SharePoint 2010.

Below is the code to delete the webpart using SharePoint 2010 client object model:

ClientContext ctx = new ClientContext("http://SiteURL");
Web oWeb = ctx.Web;

File oFile = oWeb.GetFileByServerRelativeUrl("/default.aspx");

LimitedWebPartManager limitedWebPartManager =
oFile.GetLimitedWebPartManager(PersonalizationScope.Shared);

ctx.Load(limitedWebPartManager.WebParts);

ctx.ExecuteQuery();

if (limitedWebPartManager.WebParts.Count > 0)

WebPartDefinition oWebPartDef = limitedWebPartManager.WebParts[0];

oWebPartDef.DeleteWebPart();

ctx.ExecuteQuery();