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

sharepoint.stackexchange https://sharepoint.stackexchange.com/questions/5794

  •  16-10-2019
  •  | 
  •  

Question

Can somebody please tell me what is wrong with this code?

protected void Button1_Click(object sender, EventArgs e) { using (SPWeb oWebsiteRoot = SPContext.Current.Site.RootWeb) {

            SPList oList = oWebsiteRoot.Lists["Tasks"];

            SPQuery oQuery = new SPQuery();
            oQuery.Query = "<Where><Eq><FieldRef Name='Status'/>" +
                "<Value Type='Text'>Completed</Value></Eq></Where>";
            SPListItemCollection collListItems = oList.GetItems(oQuery);

            foreach (SPListItem oListItem in collListItems)
            {
                Response.Write(SPEncode.HtmlEncode(oListItem["Title"].ToString()) +
                    "<BR>");
            }
        }

    }
Was it helpful?

Solution

Basically you should not dispose the Rootweb, if you are using the SPContext. Microsoft has updated the best practices

here is one example mentioning

http://blogs.msdn.com/b/rogerla/archive/2008/10/04/updated-spsite-rootweb-dispose-guidance.aspx

OTHER TIPS

Are u disposing any SPWeb or SPSite object that you intantiated using the SPContext object? If so then you need not to dispose any of them.

Licensed under: CC-BY-SA with attribution
Not affiliated with sharepoint.stackexchange
scroll top