Get user from Person or Group Field in Sharepoint List


There is a situation I need to add item to list and send mail to person who is on the same item xxxx field. Here xxxx is the person or group field and I set show field as “Name” [!i.e Display Name]  in list settings .  If we try to get values using properties.listItem[xxxx] it returns a junk characters with DisplayName and again we need remove the junk characters and query to user profiles to get the mail id. Sometimes [user profile not synchronized well] it didn’t query to get value based on “DisplayName”.

So this situation I try to get the actual user of the filed instead of DisplayName. then i try the following code in event receiver. 

SPFieldUser userField = (SPFieldUser)properties.OpenWeb().Lists[listName].Fields.GetField("xxxx");
SPFieldUserValue fieldValue=(SPFieldUserValue)userField.GetFieldValue(properties.ListItem["xxxx"].ToString());
accountName = fieldValue.User.LoginName;

here fieldValue.User is SPUser,  the SPUser.logingName returns Account name of the user. However finally I got mail id from user using Email Property of SPUser.
MaiId=fieldValue.User.Email
 

Comments

  1. I am getting error
    Unable to cast object of type 'Microsoft.SharePoint.SPFieldText' to type 'Microsoft.SharePoint.SPFieldUser'.
    foreach (SPListItem item in oCollection)
    {
    string sites = null;
    SPList lst = oSite.OpenWeb("/SiteName/", false).Lists["User Profiles"];
    SPFieldUser userField = (SPFieldUser)lst.Fields.GetField("User Name");
    SPFieldUserValue fieldValue = (SPFieldUserValue)userField.GetFieldValue(item["User Name"].ToString());
    htmlOutput += fieldValue.User.ID;
    }

    oSite is SiteCollection Object
    appreciate you help

    ReplyDelete

Post a Comment

Popular posts from this blog

PAGE NOT FOUND ERROR PAGE IN SHAREPOINT 2013

Hide the Upload Button of the Doucment Library

Get Host site list items in SharePoint Hosted App.