manoj´ssharepointblog

SharePoint Blog

Adding and Removing web parts programmatically in SharePoint

Leave a comment

Here is how to add and remove web parts on a SharePoint 2010 web page.  First of all you need to know what Web and Page you want to move the web parts on.  The web is the site collection that you created for that site

Adding Web Parts

publicvoid AddWebPart(SPWeb web, string pageURL, System.Web.UI.WebControls.WebParts.WebPart webPart, string zoneID, int zoneIndex)
{
SPLimitedWebPartManager webPartManager = web.GetLimitedWebPartManager(pageURL, PersonalizationScope.Shared);
webPartManager.AddWebPart(webPart, zoneID, zoneIndex);
webPartManager.SaveChanges(webPart);
web.Update();
}
This function uses the SPLimitedWebPartManager to manage the web parts on a particular page. The zoneID is web part zone name from the master page to move the web part to and zoneIndex is the position that the web part should take within the given zone. So the lower the number the higher the web part will appear on the page. IT IS VERY IMPORTANT TO CALL SaveChanges BECAUSE WITHOUT IT NOTHING WILL HAPPEN!

Removing Web Parts

public void RemoveWebPart(SPWeb web, string pageURL, string webPartTitle)
{
SPLimitedWebPartManager webPartManager = web.GetLimitedWebPartManager(pageURL, PersonalizationScope.Shared);
IEnumerable <WebPart> webPartList = from System.Web.UI.WebControls.WebParts.WebPart webPart in webPartManager.WebParts
where webPart.Title == webPartTitle select webPart;
foreach (System.Web.UI.WebControls.WebParts.WebPart webPart in webPartList.ToList())
{
webPartManager.DeleteWebPart(webPart);
}
web.Update();
}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s