Monday, October 17, 2011

SharePoint 2010 WebPart Properties not saving

I lost many time to find the way to save properties of a custom web part in Sharepoint 2010.
All my classes, methods, properties are defined correctly, but when I deploy web part and I try to save props, values were not saved and web part load with his default values.

Then I search for solution and I found that it is due to disposing the current web (SPContext.Current.Web).

I understood that I don't have to dispose SPContext.Current.Web object in my code and neither use using(SPWeb web = SPContext.Current.Web).
The solution is to use directly

SPWeb web = (new SPSite(SPContext.Current.Site.ID)).openweb(SPContext.Current.Web.ID);


to initiate a new web object and then dispose it after using.

The Save button finally saved properties values!