The webpart manager class saves the information about webparts in the database which is specified using personalization provider. When the webpart is added at runtime on the asp.net page, personalization data is not updated and so the changes are lost after the postback or new request for the page.
Thus to preserve the webparts added at runtime we have to update the personalization database for changes.
To achieve this follow the below steps
1) Create a class that extends the WebPartManager class
2) Create a method to add the new webpart
3) In the method to add the webpart, use the AddWebPart() method to add the webpart and then Call the SetPersonalizationDirty() method to indicate that the personalization data needs to be updated. This will make the webpartmanager to update the personalization data thereby preserving the dynamically added webpart between postbacks and subsequent requests.
//Extends WebPartManager
{
public void Add(GenericWebPart webpart, WebPartZoneBase zone,
int index)
{
// add webpart to zone
AddWebPart(webpart, zone, index);
// set personalization as dirty so that the new webpart is saved
SetPersonalizationDirty();
}
}
To use the above class to add a webpart dynamically :
customWebPartManager.Add(webpart, zone, 1);
Extending the WebPartManger is required because the method SetPersonalizationDirty() is a protected method. Similarly SetPersonalizationDirty() method can be used to preserve other runtime changes to the page like removing and moving webparts.
Please share your thoughts and comments for this post
Thanks,
Reetesh