Get domain account from Person field

16/07/2014 11:49

 

//If you have Sharepoint field of Person type (SPUser, people picker), you cannot read login name as follows

(item["yourPersonFieldName"] as SPUser).LoginName, because

item["yourPersonFieldName"] returns 6;#User DisplayName,

 

You have to convert field to SPFieldUser and then retreive correct values

 

string domainAccount = item["yourPersonFieldName"] as string;
 if (!string.IsNullOrEmpty(domainAccount))
 {
                 SPFieldUser userField = (SPFieldUser)list.Fields.GetField("yourPersonFieldName");
                 SPFieldUserValue userFieldValue = (SPFieldUserValue)userField.GetFieldValue(domainAccount);

                  string domAccount = userFieldValue.User.LoginName;
 }

or use a function in context of  ListHelpe r

 public static SPUser GetUserFieldValueFromItem(SPListItem item, string userFieldStaticName)
        {
            string spUser = ListHelper.GetStringPropertyFromField(item, userFieldStaticName);
            if (!string.IsNullOrEmpty(spUser))
            {
                SPFieldUser userField = (SPFieldUser)item.Fields.GetField(userFieldStaticName);
                SPFieldUserValue userFieldValue = (SPFieldUserValue)userField.GetFieldValue(spUser);

                SPUser user = userFieldValue.User;

                return user;
            }
            else
            {
                return null;
            }
        }