I was writing code using SPWeb under the impression that “using” statement takes care of disposing objects.
My Function was something like the one shown below:

public void LoadFunction()
{
using (SPWeb ospWeb = SPContext.Current.Web)
{
….Logic
}
}

However,I kept getting the error “Trying to use an SPWeb object that has been closed or disposed and is no longer valid.”
I realized, we should dispose off the SPSite object and not the SPWeb object directly.

So,I modified the code as shown below:

public void LoadFunction()
{
using(SPSite spSite=new SPSite(SPContext.Current.Web.Url))
{
using (SPWeb spWeb = spSite.OpenWeb())
{
….Logic
}
}
}

This solved the problem of “Trying to use an SPWeb object that has been closed or disposed and is no longer valid.”

Advertisements