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.
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