Sunday, April 7, 2013

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


Hi,

I got the below error post deploying my web part on the page.
Finally I got the issue from our Lead
In the code I was writing code as below
using (SPSite site = SPContext.Current.Site)
{
using (SPWeb web = site.OpenWeb())
       {
       }
}

Generally once control comes out of the using block,it disposes all the objects inside that automatically.
so when I was writing code as below,it means I am saying to dispose the current context object which is not suppose to   
using(SPSite objsite = SPContext.Current.Site)

That’s why I have been guided to write as below
using (SPSite site = new SPSite(SPContext.Current.Site.Url))
                {
                    using (SPWeb web = site.OpenWeb())
                     {
                     }
                                      }
It means,we are instanatiating new SPSite object by using in using block,while coming out of loop it disposes the newly created SPSite object.



No comments:

Post a Comment