Home > Uncategorized > Using SPListItemCollections indexer to get SPListItem returns different/reset item every time appearing to not save changes

Using SPListItemCollections indexer to get SPListItem returns different/reset item every time appearing to not save changes

While in a hurry to test some code I discovered that calling the following will not actually save your change:

spListItemCollection[0][“Title”] = “Hello World”;
spListItemCollection[0].Update();

Instead you need to store the SPListItem returned by the first indexer call and then use it to set and update.

var spListItem = spListItemCollection[0];
spListItem[“Title”] = “Hello World”;
spListItem.Update();

This indicates that even though its a property, the indexer is giving you a new or reset instance of the SPListItem everytime you ask for the same index.

Normally I would have refactored this and used a variable from the get go and so I would have never seen this. This just goes to show even the ones that build the framework don’t even follow their own best practices so always assume the worst and store objects in variables first before using them.

Advertisement
Categories: Uncategorized
  1. No comments yet.
  1. No trackbacks yet.

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 )

Connecting to %s

%d bloggers like this: