Nick Grattan's Blog

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

When a SPFieldUserValueCollection won’t clear

leave a comment »

Some time ago I wrote about problems with updating items through an item collection (see here). Well, here’s another similar problem that has bitten me, and it’s to do with updating a SPFieldUserValueCollection object.

In this code I want to clear out the list of users configured for a multi-select user column in a list:

                SPListItem li = ...; // get a list item
                SPFieldUserValueCollection uvc = (SPFieldUserValueCollection)li["View Form Groups"];
                if (uvc != null)
                {
                    uvc.Clear();
                }
                li.Update();

The code gets the SPFieldUserValueCollection object for the field, and if it’s not null, empties the collection and updates the item.

However, the list of users is not cleared in the list item. It seems that a copy of the collection is made, and it’s the copy that is cleared. Here’s the code to correct this problem:

                SPListItem li = ...;
                SPFieldUserValueCollection uvc = (SPFieldUserValueCollection)li["View Form Groups"];
                if (uvc != null)
                {
                    uvc.Clear();
                    li["View Form Groups"] = uvc;
                }
                li.Update();

In this case, the modified SPFieldUserValueCollection is copied back into the field and the list item updated.

Advertisements

Written by Nick Grattan

January 2, 2011 at 9:58 am

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: