When an SPListItem won’t Update or Change
Here’s a problem that recently bit me. This code executes a query that returns a single SPListItem and then attempts to change the approved status through the SPListItemCollection:
SPListItemCollection lic = list.GetItems(query);
lic[0].ModerationInformation.Status = SPModerationStatusType.Approved;
lic[0].Update();
Strangely enough, before calling the change to “Status” (second line) the status was “Pending” and *after* the call the status was still “Pending”!
However, assigning to a SPListItem and updating through this object changes the approved status as expected:
SPListItemCollection lic = list.GetItems(query);
SPListItem li = lic[0];
li.ModerationInformation.Status = SPModerationStatusType.Approved;
li.Update();
It seems the SharePoint object model cannot handle repeated calls through the item collection to the same list item object – perhaps it creates a new temporary object each time?
Yes, the indexers are heavyweight and don’t behave like you’d expect. When you make the first lic[0] call, it returns object #1, when you make the second call, you get object #2. So you’ve changed the Status property on object #1, but call the Update() method on object #2 (which does not know about any changes to its Status property).
This behavior is consistent between other objects like SPWeb, SPSite, SPList, etc. Treat collection indexers as “create brand new object” method calls, and you’ll be fine.
Peter
November 12, 2008 at 9:02 pm
Thanks for your comments – very helpful.
The indexer acts more like a factory that an indexer, and so this behavior is not expected. I guess the indexer is instantiating the returned object from an element in an XML document each time it’s requested and not maintaining a list of the object’s that have been returned.
Like all things, when you know….
Nick
Nick Grattan
November 12, 2008 at 10:54 pm