Wednesday, November 2, 2011

How to get SPUser or SPGroup from Person or Group field

Ok, here is the thing - you have person or group field in SharePoint list and you want to programmatically get the user or person.

This code snippet gets SPUser from User or Group field in the list when multiple choice and Groups are not allowed in the field:
//get SPUser
SPFieldUser userField = (SPFieldUser)item.Fields.GetField("Users");
SPFieldUserValue userFieldValue = (SPFieldUserValue)userField.GetFieldValue(item["Users"].ToString());
SPUser user = userFieldValue.User;


This part of code would help you to get SPUser when multiple choice is allowed and groups are not allowed:

//Multiple choices are allowed
SPFieldUser userField = (SPFieldUser)item.Fields.GetField("Users");
SPFieldUserValueCollection userFieldValueCollection = (SPFieldUserValueCollection)userField.GetFieldValue(item["Users"].ToString());
foreach (SPFieldUserValue userFieldValue in userFieldValueCollection)
{
    Console.WriteLine("     " + userFieldValue.User.LoginName);
}


And when group is allowed  you can use this code(In this part I'm not quite sure about solution. I wrote it, It's working, but maybe there is better approach so if you know better do not hesitated to comment it :) ):

//Group or User are allowed
SPFieldUser userField = (SPFieldUser)item.Fields.GetField("Users");
SPFieldUserValue userFieldValue = (SPFieldUserValue)userField.GetFieldValue(item["Users"].ToString());
//Tries to get SPUser
if (userFieldValue.User != null)
{
   SPUser user = userFieldValue.User;
}
//if the field contain group
else
{
  SPGroup group = web.SiteGroups.GetByID(userFieldValue.LookupId);
}


Happy coding ;)

5 comments:

  1. thanks a ton David :)

    ReplyDelete
  2. Great Post (y)
    Just one more thing if my userField.AllowMultipleValues== true
    then how can I add my current user or any user to the SPFieldUserValueCollection of this userField ???

    ReplyDelete
    Replies
    1. Hi,
      Thanks ;)
      Look at this, it may help you: http://exxlence.com/2009/02/08/simplify-getting-and-setting-fields-of-type-spfielduser-spfieldurl-and-spfieldlookup-using-extension-methods/

      Let me know if that is what you need ;)

      Delete
  3. Thanks, this helped me alot. Just one thing to make sure if the field allows multiple selection of users, then it's a SPFieldUserValueCollection type.

    ReplyDelete