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.
thnxxxxxxxxxxxxxxx