Friday, April 20, 2012

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.

No comments:

Post a Comment