1

So I created a custom list with a person field. The person field has multiple names of people. What I want to do is get an Item' [person field] data and put it into a SPUserCollection, I tried to do something like this:

SPUserCollection users = (properties.Web.Lists[listName].GetItemById(properties.ListItemId)[people]); 
foreach(spUser in users)
{
my awesome code;
}

anyone know how to solve this, thanks!

  • I don't know what properties is, but if it is SPItemEventProperties then I would like to note that you can do properties.ListItem. And now that Egor pointed out you get SPFieldUserValueCollection, give you have a SPFieldUser field I will just leave this as a comment :) – eirikb Jan 15 '13 at 6:53
2
SPFieldUserValueCollection userVals = (SPFieldUserValueCollection)item["UserName"];
foreach (SPFieldUserValue userVal in userVals)
{
// your code
  SPUser user = userVal.User;
}

Hope it helps..

2

If your person field is of type User or group with multiple values allowed, then its value in code is represented by SPFieldUserValueCollection class.

Below is my code example. This is an extension method, which takes SPListItem and Guid of field to convert it to array of SPUser. You can chage Guid to the name of the field if you need to:

    public static SPUser[] GetUserCollectionField(this SPListItem Item, Guid FieldId)
    {
        SPFieldUserValueCollection UserValue = Item[FieldId] as SPFieldUserValueCollection;
        if (UserValue == null)
            return null;
        return UserValue.Select(u => u.User).ToArray();
    }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.