Close/Open Web Parts Programmatically

I didn't see a lot of post that shows you how to close and open web parts programmatically. I figured I'll writer one just in case I forget how to do it later.

You have to work with WebPartManager class for working with web parts. To get the web part manager, you can do the following:

SPFile page = site.GetFile("pageUrl")
SPLimitedWebPartManager webPartMngr = page.getLimitedWebPartManager(PersonalizationScope.Shared);

Once you have the WebPartManager, you can get the web part that you want to close by doing:

Foreach (WebPart webPart in webPartMngr.WebParts)
{
if (webPart.Title == "testWebPart")
{
webPartMngr.CloseWebPart(webPart);
webPartMngr.SaveChanges(webPart);
}
}

The SaveChanges() has to be done else it just won't work. After the web part is closed, you can still find it in webPartMngr.WebParts collection to re-open it. The code is basically the same as how you would close it. Just change the CloseWebPart() to OpenWebPart() instead.

Comments

Popular posts from this blog

SharePoint 2013 App Details Page Error

SharePoint 2013 - Working with Display Template for Content Search Web Part

Add spell check dictionary in SharePoint 2010, SharePoint 2013, and Office 365