Error: Trying to use an SPWeb object that has been closed or disposed and is no longer valid.

You may have noticed this error while doing SharePoint development. I also faced it the other day hence thought of penning it down so that someone else could benefit from this
You typically get this error when you unknowingly try to dispose the SharePoint Objects. We try to perform the SharePoint best practices and this sometime may lead to few nervy moments during development.
For e.g.
The following code will give you the above mentioned error “Trying to use an SPWeb object that has been closed or disposed and is no longer valid

using(SPWeb web = SPContext.Current.Web)
{
   //your code
}

At the first look nothing seems wrong with the above code, but the real culprit is the using statement above as it automatically disposes the SPWeb object. SPContext allows you to reference to the object SharePoint has created and hence should not be disposed as it will destabilize SharePoint operations.

So the moral of the story is to do not dispose the SPContext objects in your code.

SPWeb web = SPContext.Current.Web

Related Post

1 thought on “Error: Trying to use an SPWeb object that has been closed or disposed and is no longer valid.”

Leave a Reply

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