Monday, October 06, 2008

Saving WebPart Personalization Properties

If you tried to modify some properties of your web parts and save them from server code you probably noticed that there are some differences in the way this is handled in the SharePoint web parts namespace and in the ASP.NET web part namespace. Particularly if you are trying to save web part properties from code that is outside of the actual web part.

In SharePoint land the SPWebPartManager class has the SaveChanges(webpart) method, which allows us to save the properties of any web part on the page from any code location. However in the ASP.NET namespace this method is not available. Certainly one option is to switch to the SharePoint web parts namespace, however this is not recommended and prevents the web parts from being used in pure ASP.NET environment.

The only viable alternative I was able to find out is to expose the protected WebPart.SetPersonalizationDirty() in all my custom web parts:

   1:  public class CustomWebPart:WebPart
   2:  {
   3:  ...
   4:          public void SaveProperties()
   5:          {
   6:              base.SetPersonalizationDirty();
   7:          }
   8:  ...
   9:  }

Then I can make changes to my web parts' properties and save them from other page events, such a Page_Load etc.

   1:  WebPartManager wpm = WebPartManager.GetCurrentWebPartManager(Page);
   3:  CustomWebPart wp = wpm.WebParts[0] as CustomWebPart;
   4:  wp.Title = "New name, new property";
   5:  wp.SaveProperties();

Seemingly easy, but for some reason took my colleague and me tons of times to figure out.