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!