Monday, December 20, 2010

Trying to use an SPWeb object that has been closed or disposed and is no longer valid.

"Trying to use an SPWeb object that has been closed or disposed and is no longer valid" error message is very common amongst developers dealing with the SharePoint object model. Here is how the error looks like:


The reason behind this is a silly mistake that developers do, when trying to use the SPSite/SPWeb objects. Here is the bad code that resulted in the error:



I used the using clause alongwith the SPContext.Current.Site which resulted in this error, it implicilty disposes the SPSite object which should not be done when using the SPContext object. Lets refactor the code a little bit and have a look at the good code snippet which resolved this issue:



Thats about it, my code started working when I removed the using clause from the SPContext.Current.Site. The same thing is true when you try to either explicitly/implicitly Dispose the SPContext.Current.Web object. So moral of the story never dispose SPContext objects either implicitly leveraging the using clause or explicitly by using Dispose method from in your finally block.

Watch out for the SharePoint Object Model coding best practices at : http://www.sharepointfix.com/2008/12/best-practices-disposing-sharepoint.html