Here we will discuss how to solve error Trying to use an SPWeb Object that has been closed or disposed and is no longer valid which comes while working with SharePoint 2013/2016 server object model.
Recently I was trying to retrieve list templates using SharePoint 2016 server object model in SharePoint 2016. I was using Visual Studio 2017 and was retrieving list templates inside a visual web part for SharePoint 2016.
I was using the below SharePoint server object model code.
using (SPSite oSite = SPContext.Current.Site)
{
using (SPWeb oWeb = oSite.RootWeb.Site.OpenWeb())
{
//Below is the code
}
}
But it gave error as Trying to use an SPWeb Object that has been closed or disposed and is no longer valid, and the error looks like below:
Trying to use an SPWeb Object that has been closed or disposed and is no longer valid
The problem was coming because of the using block I was using the code.
Since I was using SPContext.Current.Site, I should not use the using block. SharePoint will do automatically memory management. It will dispose unused objects automatically.
So to resolve the issue, I modified the code like below:
SPSite oSite = SPContext.Current.Site;
{
SPWeb oWeb = oSite.RootWeb.Site.OpenWeb();
{
//Below is the code
}
}
You may like following SharePoint server object model tutorials:
- Add, Update, Delete & Display List items in Gridview Programmatically in SharePoint 2016
- SharePoint 2013 web parts tutorial
- Change List or Document library URL in SharePoint 2013
- Create subsite in SharePoint 2013/2016 programmatically
- Implement Custom SuiteBarBranding Delegate Control in SharePoint 2013
- Various ways to add item into a SharePoint 2013 List
I hope this tutorial helps to resolve Trying to use an SPWeb Object that has been closed or disposed and is no longer valid error in SharePoint 2013/2016.
I am Bijay from Odisha, India. Currently working in my own venture TSInfo Technologies in Bangalore, India. I am Microsoft Office Servers and Services (SharePoint) MVP (5 times). I works in SharePoint 2016/2013/2010, SharePoint Online Office 365 etc. Check out My MVP Profile.. I also run popular SharePoint web site EnjoySharePoint.com