validationsharepoint-2010controlspeoplepicker

How to get email address from a People Picker control after EnsureUser is called in SharePoint?


I have one People Picker and Label on a page, and once I ensure that the user is available in Active Directory, I need to bind the user's email address to the label control. Where would the code for this need to be written? Should it be in the PageLoad() event handler?


Solution

  • yes, you can access the SPUser object (which holds the email property) like this:

    var accountName = peoplePicker.Accounts[0];
    
    //this will create a new account on SharePoint if a user with the given accountName does not exist
    var user = web.EnsureUser(accountName); 
    
    lblEmail = user.Email;
    

    peoplePicker obviously is the people picker control, web is an instance of the current web you are in (you can use the web of the SPContext.Current.Web aswell).

    There is not specific event that fires when you enter a username in the people picker and hit enter, however you can set the AutoPostback property to true that then fires a generic postback which you can handle via Page_Load...

    Define the PeoplePicker in your markup as followed:

    <SharePoint:PeopleEditor AutoPostBack="true" ID="peUser" runat="server" />
    

    In the Page_Load you simply check whether the people picker holds one (or more, depends) accounts with the Accounts property and then perform your task...

    hope this helps