May 19, 2011

When not to use SPContext.Current.Web

This morning I was trying to change a title of a webpart that I have in my SharePoint site, when I noticed that its not working and throwing the following error

Cannot save the property settings for this Web Part. Exception occurred. (Exception from HRESULT: 0x80020009 (DISP_E_EXCEPTION))


I was surprised since nothing much has changed in that page since the last time we created it!

So I started looking for an answer, and as usual the first spot was the SharePoint logs and that proved useless as it only showed the error message that the webpart was displaying, duh!

Next step was to run Visual Studio in debug mode to see if I can catch any exceptions on the page that our custom webparts may have caused, and that didn’t work either.

the final step was to remove the webparts of the page one by one to see which one was causing the issue and viola! When removing the webpart, the error disappeared for all the other webparts. So I decided to open up Visual Studio again and inspect the code for that webpart.

This webpart was doing a lot of things, but one thing I have noticed was the use of SPContext.Current.Web in one of the methods and while I was searching the web for an answer, some people mentioned that this call causes issues, so I replaced that call with using (SPWeb web = SPContext.Current.Site.OpenWeb()) and that worked! Unbelievable.

Lessons learned: do not use SPContext.Current.Web  or even SPControl.GetContextWeb(Context) in your webparts as that causes issues with the webpart page.

1 comment: