Get SPUser from Person or Group field

Fri, Sep 28, 2012 One-minute read

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.,

<br /> item["MyPersonField"]<br />

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:

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