Tuesday, 26 June 2007

"Trying to use SPWeb object that has been closed.." Error

We were getting “Trying to use an SPWeb object that has been closed or disposed and is no longer valid.” in our MOSS -Workflow project.

After investigating all the source codes, I found the error causing statement in WebPart class.

The best practice is to dispose objects either by calling Dispose() in finally block or with using clause.

The snippet causing problem in our project was

SPGroup group;
using (SPWeb web = SPContext.Current.Web)
{
group = web.Groups[“Administrators”];
this.DisplayText = "Submit for Approval";
:
:
}

Here, the object is not really created in the memory, only the reference to the exisiting object is got and used. We should not dispose the current context web object manually in our code.

More information about best practice can be found at
http://msdn2.microsoft.com/en-us/library/ms778813.aspx

Happy Coding :)

2 comments:

Unknown said...

thanks,

That was very helpful

mindfullness said...

Thanks For solution but i would like to know abolut when i used this code
using(SPSite site = new SPSIte("SIteURL");
{
using(SPWeb web = site.openWeb())
{
My Logic...
}
}
I got this error but when use this using(SPWeb web = new SPSite(SPContext)
{
My Logic
}
That's code run fine

What is difference b/w them. I have already used using statemnet in both but error occured in first.
So, let my clarify about the problem.
Thanks.