GetListItemSPUser

Aug 23, 2011 at 10:29 AM

I think getting a SPUSer out of a field is a very common task:

	/// <summary>
        /// Returns a SPUSer from a listitem field.
        /// </summary>
        /// <param name="item">The item</param>
        /// <param name="fieldName">the fieldname</param>
        /// <returns>the spuser from the field</returns>
        public static SPUser GetListItemSPUser(this SPListItem item, string fieldName)
        {
            if (item != null && item.Fields.GetField(fieldName) != null)
            {
                SPFieldUser fieldUser = item.Fields.GetField(fieldName) as SPFieldUser;
                SPFieldUserValue fieldUserValue = fieldUser.GetFieldValue((string)item[fieldName]) as SPFieldUserValue;

                return fieldUserValue.User;
            }
            else if (item[fieldName] == null)
            {
                return null;
            }
            else
            {
                throw new ArgumentNullException("item and or field is null");
            }
        }

Regards from Munich

Max