Monday, 12 May 2008

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

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

When you get the error message above it is most likely that you have got a reference to the SPWeb object by using the SPContext as shown below

SPWeb web = SPContext.Current.Web;

There is no problem with using this method but you need to make sure that you do not close or dispose this SPweb object becase the SPContext.Current.Web is used by the Page and all the controls on the page.

So you should not use this web object in Using statements also.

4 comments:

Rajiv said...

But if we donot dispose the SPWeb object than what about the instance that we created for SPWeb.

Wheather it will be an overhead or it will be automatically handled somewhere.As generally we dispose instances

Suprej Venkat said...

Hi Rajiv, if you create an instance of the SPWeb object using the SpContext.current.web than this will be automatically disposed by the page after rendering so you do not need to worry about it

Anonymous said...

Hi Rajiv,
I m still getting this error even after I replaced the code with correct one. In case if I close the root web how can I get rid of this error?
Regards,
Ravi

Soni said...

Thanks Suprej, this blog solved my problem which i was facing from 2-3 days