Get SPUser from Person or Group field

On any list, you can define a new column as a type of “Person or Group”. In event handlers or workflow, you may want to grab this value as use it as a real SPUser object, which will expose the name and email address, for example. Unfortunately if you just grab the value of the field, e.g.,


item["MyPersonField"]

you’ll end up with a string that looks a bit like this:

15;#DOMAIN\Matt Thornton

The gubbins before the login name is how SharePoint stores which group the person is a member of. You could then start messing about with the string and looking up in web.AllUsers, but, fortunately, there is a better way. This simple function will take then name of the field, and the SPListItem that has the value of that field:


public SPUser GetSpUserFromId(string fieldName, SPListItem item)
{
var userField = (SPFieldUser)item.Fields.GetField(fieldName);
var fieldValue = (SPFieldUserValue)userField.GetFieldValue((string)item[fieldName]);
var user = fieldValue.User;
return user;
}

HTH.

Be the first to comment

Leave a Reply

Your email address will not be published.


*