Exception Trying to use an SPWeb object that has been closed or disposed and is no longer valid.
Have seen many developers struggling with this exception and its a common mistake that people make in their code.
SPWeb, SPSite objects leak memory if they are not disposed properly. The problem is so much talked about that as soon as we think of SPSite and SPWeb we unconsciously put
using (SPWeb spweb = blah blah)
However when you use SPContext to get site or web object you should not be using “USING” or you should not dispose that object. SPContext is passed to another web part on the page and SharePoint will dispose it when done.
Hence if you have been using (SPSite spsite = SPContext.Current.Site) it is wrong. It might not always break as you might just have one web part in your code but you will see it break as soon as you add another web part and may be try to check in the page.
so change
using (SPSite spsite = SPContext.Current.Site)
to
SPSite site = SPContext.Current.Site.
Comments
Anonymous
October 03, 2014
Thanks It was very helpful have been struggling and was lucky to find this post and even luckier coz it looks like you just posted itAnonymous
July 16, 2015
Thank you! This was really helpful!Anonymous
October 08, 2015
Thank you! This was really great explanation