Quick tip: Troubleshoot SP error “Trying to use an SPWeb object that has been closed or disposed and is no longer valid”

This error definitely comes from not following Microsoft’s best practices. There’s a great article on MSDN about best practices that everyone should have a read through. Click to read now Best Practices: Using Disposable Windows SharePoint Services Objects.

Your code will most probably look a bit like this:

using (SPSite scName = SPContext.Current.Site)
{ using (SPWeb swName = SPConext.Current.Web) {}}

Or, something like that. Maybe you’re only using the SPContext to get the SPSite and then use the OpenWeb() method to get the SPWeb object.

Whatever you’re doing, you’re on the wrong track. The SPContext, used with using, will implicitly dispose of your object. That’s the reason why you’re getting that error. You’re trying to reference an object that is not there anymore.

In order to create the object in the memory so that it will not be disposed and so that you can access it without it being disposed, you will have to change your coding.

First off, you can’t use “using” alongside “SPContext.Current.Site” or “.Web” . What you need to do is the following:

SPSite scName = SPContext.Current.Site; (instead of sticking it into a using statement).

Then, you can reference that object from your SPWeb and not fear that it will have been disposed. But, as I said, you can’t use SPContext with “using”. Instead, try the following:

using (SPWeb swName = scName.Openweb() {}

That ought to fix it 🙂
Happy coding then.

SPSite scName = SPContext.Current.Site; // NO USING
using (SPWeb swName = scName.Openweb() {} //NO SPContext!

MGR: the Intelogist

About MGR: the Intelogist

SharePoint Server developer, turned Sitefinity developer, turned Angular developer, turned SharePoint Online consultant, turned Unily consultant, turned O365 consultant... Never a dull moment!

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes:

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> 

This site uses Akismet to reduce spam. Learn how your comment data is processed.