MOSS Error – Operation is not valid due to the current state of the object


Hi Guys,

Today I am posting another very short but very interesting post which will save your hours of efforts and some hairs too.

Problem Statement: SPListItem.Update() and SPListItem.SystemUpdate() calls fails with the following error – ‘Operation is not valid due to the current state of the object’

One liner solution: Do NOT call SPListItem.Update() inside Evelvated Permission’s delegate

Detailed Solution: You must instantiate and populate SPSite and SPWeb object inside elevated Permission’s delegate but you should NOT call SPListItem.Update() or SystemUpdate() method inside your delegate control.

Here is the snippet of code which works (I wrote the following snippet in Microsoft Word – Please rectify if there are any complier errors)

SPListItem anItem = null;

SPSecurity.RunWithElevatedPrivileges(delegate(){

using(SPSite aSite = new SPSite(“URL”))
{
using(SPWeb aWeb = aSite.OpenWeb())
{
SPList aList = aWeb.Lists[“ListName”];
anItem = aList.GetItemByID(1); //Or you can query your item.
}
}
});

anItem[“Field1”] = “ValueOfField1”;
anItem[“Field2”] = “ValueOfField2”;
anItem.Update();

I hope it will help you guys.

Advertisements

1 Comment

  1. amna

    thnxxxxxxxxxxxxxxx

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: