by Andreas

Sharepoint 2010 Development – SPWeb disposal error

A common error for any Sharepoint 2010 developer is the following:

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

image

You’ve obviously disposed of an SPWeb instance somewhere in your code which in turn eliminates further execution on this object. But why does this happen?

When retrieving the SPWeb object (which is a site under a site collection) there are multiple possibilities:

SPSite siteColl = new SPSite(“http://yourserver“);
SPWeb site = siteColl.OpenWeb();

or, more likely if you see this error:

SPWeb site = SPContext.Current.Web;

The difference between these two is that the latter actually doesn’t open a site, you’re getting it from the current context which is used by both the page and possibly other controls. Not a problem – until you dispose of it. Assuming you are following other “best practices” you’re running your code within a using(SPWeb site = SPContext.Current.Web) block, which automatically disposes of the object afterwards. This is where your error message appears.

So, in other words: create a new site collection instance by using the new SPSite(“http://yourserver”) rather than just fetching it from the current context.

Update: or if you insist on not knowing your own url: new SPSite(SPContext.Current.Site.Url)

image