Saturday 12 October 2013

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


This error occurs when we try to use "SPContext.Current.Web" in the Using statement. If you use "SPContext.Current.Web" in the Using statement,then it forces to SPSite object Dispose() method to be invoked. You did not create that SPSite object, so you should not dispose it manually. Never dispose of anything in SPContext. Sharepoint will take care of SPSite object Dispose() and disposes it when its work gets done.

So, remove SPContext from the Using statement and modify your code as below:

                string siteUrl = SPContext.Current.Web.Url;
                 using (SPSite spsite = new SPSite(siteUrl))
                {
                    using (SPWeb spweb= spsite.OpenWeb())
                    {
                        //Your Code
                    }
                }


The above code works fine without disposing SPSite object.

No comments:

Post a Comment

Total Pageviews