Nick Grattan's Blog

About Microsoft SharePoint, .NET, Natural Language Processing and Machine Learning

When an SPListItem won’t Update or Change

with 2 comments

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?

Advertisements

Written by Nick Grattan

November 12, 2008 at 8:27 pm

2 Responses

Subscribe to comments with RSS.

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

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


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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s

%d bloggers like this: