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

Some times when we use the Sharepoint object model to get or set data we get the following error “Trying to use an SPWeb object that has been closed or disposed and is no longer valid.” in our MOSS or WSS environment.
Trying to understand whats under the hood i digged in couple of blogs and forums and figured out whats going on with the object model.

There are two cases where you use the SpContext to get to the site directly or SpSite and the SpWeb to get through the site to grab and set data under the entire collection.

Process 1:
One way is to use the SPSite.OpenWeb()
OpenWeb will return a Web object in a different memory space
Use this object when you try to read and write data.In other words use this when you are modifying or changing data,use OpenWeb and dispose.

Process2:
SPContext.Current.Web method
CurrentWeb will return the Web object using the current memory space and thread.
Use this when you fetch and display the data, No need of disposing the spcontext object. If you try to dispose it . you will end up in getting this error.

Leave a Reply

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

Bitnami