One of my collegue working on custom Web Part development and got this error “Trying to use an SPWeb object that has been closed or disposed and is no longer valid” It is very common amongst developers dealing with the SharePoint object model. Here is how the error looks like”
It is a matter of Code. 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:
In above code snippet, developer used “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. Which is not ideal to use. Lets rectify the code a little bit and have a look at the good code snippet which resolved this issue:
After removing the “using” clause from the SPContext.Current.Site code works fine!
Same thing applies when try to dispose either explicitly/implicitly the SPContext.Current.Web object.
So, NEVER dispose SPContext objects either implicitly pulling the “using” clause or explicitly by “using” Dispose method from “Finally” block.