Tuesday, 19 February 2008

Retrieving an SPUser object from an SPListItem

Whilst coding a Timer Job I came across a requirement to extract the user's email address from a User Type column in a SharePoint list item. I must admit, naively I thought it would be as simple as casting the ListItem["user"] as SPUser, but to my surprise this produced a lovely error.

Finally after dredging through the SDK and other blogs/forums and my determination not to have to use the SPSite.AllUsers, I cam up with this solution which seems to work nicely

Simple and effective.

Code Snippet
  1. SPFieldUser userField = listItem.Fields.GetFieldByInternalName("InternalFieldName") as SPFieldUser;
  2. SPFieldUserValue userFieldValues = listItem[userField.Title] as SPFieldUserValue;
  3. SPUser userFromListItem = userFieldValues.User;
  4. string userEmailAddress = userFromListItem.Email;

0 comments:

Post a Comment