Thursday, May 10, 2007

Getting Users from Multi-select Person or Group Fields

The following code illustrates how to extract user information for all users listed in a multiselect Person or Group field (in this case extracting all the users listed in the "Control Owners" field of the first list item in the "Controls" list) :

using (SPWeb web = new SPSite(WEB_URL).OpenWeb())
{
    StringBuilder sb 
= new StringBuilder();    
    
SPList list web.Lists["Controls"];

    
SPFieldUserValueCollection userVals (SPFieldUserValueCollection)list.Items[0]["Control Owners"];
    foreach 
(SPFieldUserValue userVal in userVals)
    {        SPUser user 
userVal.User;
          
sb.AppendLine(string.Format("{0}", user.LoginName));
    
}
}

3 comments:

Unknown said...

Hi,
I am getting problme in storing Multiple values from PeopleEditor to List.
I am using below code snippet.

if (this.peContributors.ResolvedEntities.Count > 0)
{
int usercount = 1;
SPFieldUserValueCollection users = new SPFieldUserValueCollection();

foreach (PickerEntity entity in peContributors.ResolvedEntities)
{
SPFieldUserValue user = new SPFieldUserValue(SPHelper.GetSite(HttpContext.Current).OpenWeb(), usercount++, entity.Key);
users.Add(user);
}

item["Contributors"] = users;
}
item.Update();

By doing above, only first entry is saved in the list.

yagnesh

Unknown said...

SPFieldUserValueCollection users = new SPFieldUserValueCollection();

foreach (PickerEntity picker2 in pe.ResolvedEntities)
{
userInf = new SPUserInfo();
user = web.EnsureUser(picker2.Key);
SPFieldUserValue user3 = new SPFieldUserValue(web, user.ID, picker2.Key);
users.Add(user3);

}
yeni["Contributors"] = users;

Unknown said...

Excellent post. saved my time.