Monday, 3 December 2012

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


If your using share point object model and your getting this error -

"Trying to use an SPWeb object that has been closed or disposed and is no longer valid."
The best practice is to dispose objects either by calling Dispose() in finally block or with using clause.


following is the code snippet causing the problem -

using (SPSite site = SPContext.Current.Site)
{
site.AllowUnsafeUpdates = true;
using (SPWeb web = site.OpenWeb())
{
web.AllowUnsafeUpdates = true;
SPList list = web.Lists["UserProfileInfo"];
SPListItem Item;
if(string.IsNullOrEmpty(hdnListID.Value))
Item = list.Items.Add();
else
Item =list.Items.GetItemById(Convert.ToInt32(hdnListID.Value));


Item["Initial"] = ddlInitial.SelectedIndex;
Item["FirstName"] = txtFN.Text;
Item["LastName"] = txtLN.Text;
.
.

.
.
.
.
web.Dispose();
}
site.Dispose();
}


The object is not created in the memory when you are using "using". You will find more details about the Best Practices: Using Disposable Windows SharePoint Services Objects HERE

Share This!


No comments:

Post a Comment

Translate

Total Pageviews

Powered By Blogger · Designed By Seo Blogger Templates