in

SharePoint Blogs

The Best Place for SharePoint-related Blogs

This Blog

Syndication

All About SharePoint - S.S. Ahmed - MVP Microsoft SharePoint

All About SharePoint, as the name suggests, is all about SharePoint. It has articles, tutorials, source code, FAQs, and tips about SharePoint, InfoPath, C#, Microsoft Office, SQL Server, XML, etc.

Operation is not valid due to the current state of the object

Operation is not valid due to the current state of the object

This is one of the common errors that you see during SharePoint development. There could be many reasons for this error to occur. Here I will discuss one scenario. I have noticed that sometimes calling SPContext throws this error. It seems to be a bug. The code works for the first time but throws an error if you run the same statement again (during the same session). For example, consider the following code:

SPSecurity.RunWithElevatedPrivileges(
delegate()
{
     using (SPSite site = new SPSite(SPContext.Current.Site.ID))
     using (SPWeb web = site.OpenWeb(SPContext.Current.Web.ID))

     string ItemID = web.Lists["myList"].Items[0]["ItemID"].ToString();
}
);

Interestingly, sometimes this code works but sometimes it fails after running successfully for the first time. I feel something goes wrong with the session. SPContext returns correct context when accessed for the first time but then throws the following error:

Operation is not valid due to the current state of the object

The error goes away if you remove the SPContext code and hard code the site and web values, for example:

SPSecurity.RunWithElevatedPrivileges(
delegate()
{
      using (SPSite site = new SPSite(http://server/))
      using (SPWeb web = site.OpenWeb("myweb"))

      string ItemID = web.Lists["myList"].Items[0]["ItemID"].ToString();

}

);

Obviously, we can not hard code the values in professional level applications. So, what's the solution? How can we get rid of this error? The error can be avoided if we write the same code in a different way. Here is the modified code:

SPWeb  webContext = null; //declare webContext out side the try ... catch and assign "null"

try
{

     webContext = SPContext.Current.Web; // Assign SPContext to the webContext

    SPSecurity.RunWithElevatedPrivileges(
    delegate()
   {
        using (SPSite site = new SPSite(webContext.Site.ID))
        using (SPWeb web = site.OpenWeb(webContext.ID))

        string ItemID = web.Lists["myList"].Items[0]["ItemID"].ToString();
   }
);

}

catch (Exception ex)
{

}

finally
{
    if (webContext != null)
         webContext.Dispose();
}


Now, you won't get any error. Note that we declared the webContext outside the try... catch block and used SPContext only once. You can get "site" by calling webContext.Site.ID and similarly you can get "web" by calling webContext.ID. It's important that you dispose off the object after using it.

Comments

 

Windows Vista News said:

Did you see the post at www.sharepointblogs.com

November 25, 2007 11:14 PM
 

SharePoint 2007 Link love: 12-02-2007 part four at Virtual Generations said:

Pingback from  SharePoint 2007 Link love: 12-02-2007 part four at  Virtual Generations

December 1, 2007 5:39 PM
 

Miquel said:

I get this error with this code.

try

       {

           Microsoft.SharePoint.SPSecurity.RunWithElevatedPrivileges(delegate()

           {                              

               Guid docid = new Guid(idDoc);

               Microsoft.SharePoint.SPSite sps = new Microsoft.SharePoint.SPSite("http://win2003");

               Microsoft.SharePoint.SPWeb spw = sps.OpenWeb();

               spw.AllowUnsafeUpdates = true;

               Microsoft.SharePoint.SPFile spf = spw.GetFile(docid);                

               spf.Item.Fields["Estat"].ReadOnlyField = false;

               spf.Item.Fields["Estat"].Update();

               spf.Item["Estat"] = "Modificat";

               spf.Item.Update();

               spf.Item.Fields["Estat"].ReadOnlyField = true;

               spf.Item.Fields["Estat"].Update();

               spw.Dispose();

               sps.Dispose();

           });

       }

       catch (Exception e)

       {

           Console.WriteLine(e.InnerException);

       }

Can you help me with any idea. The error is in the line spf.Item.Update();

the line

spf.Item.Fields["Estat"].Update();  seems it run ok.

Thanks

Miquel

December 4, 2007 1:33 PM
 

ssa said:

Did you check the event log? What does the inner exception say? Also, why are you calling the update function twice? My suggestion would be to run the code in debugger and change the line that causes the problem.

December 13, 2007 10:30 AM
 

SharePoint MVP Blogs said:

Operation is not valid due to the current state of the object This is one of the common errors that you

June 19, 2008 3:21 PM
 

Navdeep Madan said:

First, We you try to create custom links WebPart and render all the fields (Type, Edit, URL & Notes)

September 1, 2008 12:28 PM

Leave a Comment

(required )  
(optional )
(required )  
Add

About ssa

MOSS MVP - Over 8 years experience. 4 years SharePoint experience!

Need SharePoint Training? Attend a SharePoint Bootcamp!

Posts (c) their respective authors. Everything else (c) 2007 SharePoint Experts