Wednesday, April 04, 2007

SPListItem.Update isn't updating!

Here's a good one. Why doesn't this work:

SPList myList = myWeb.Lists["MyList"];

for (int i == 0; i < myList.Count; i++)
{
myList.Items[i]["Value"] = "42";
myList.Items[i].Update();
}

This *should* set the Value column to 42 for every item in the list. But for some reason, no exception, no Event Log entry, running with impersonation, etc etc - this just doesn't work.

The reason: laziness. Here's what does work:

SPList myList = myWeb.Lists["MyList"];

for (int i == 0; i < myList.Count; i++)
{
SPListItem myItem = myList.Items[i];
myItem["Value"] = "42";
myItem.Update();
}

myItem isn't disposable, so that should do the trick.

10 comments:

Anonymous said...

excellant....it would seem I was a bit lazy myself. Thanks for the info

Anonymous said...

Thank you, Thank you, Thank you! :-)

Hammoudeh Ahmad said...

Thanks Steve, this helped years after you wrote the post. but i didnt understand how this solved the problem?

Hammoudeh Ahmad said...

Thanks Stever, this helped me too. I had solved this issue by removing the item and adding it again but then reverted back to the way you described ... but, i didnt know how this solved the probelm! can u plz elaborate?

Anonymous said...

"lazy" .. grrr! ;)
saved my day!
thank you!

Anonymous said...

little error:
for (int i == 0; i < oList.Count;
i++)

should be:
for (int i = 0; i < oList.Count;
i++)

venugopal.v said...

Steve u rocks.... dude. Thank you.

Lucas Araujo said...

Wow! Thanks! That one really helped us!

Gustavo Santos said...

Just saved a lot of spent time! I didn't understand how it solved the problem too, but it works!

Anonymous said...

Thanks much, you have solved my problem :-)