People in the field

SharePoint again folks! When dealing with users and groups (for example with list columns), SharePoint likes to store the underlying value in it’s own special format, usually ID;#Value (e.g “1;#neboddy”). That’s all well and good, but when you need to retrieve that value and display it in a friendly format (e.g. “Mr N E Boddy”) then there’s some work to do.

Fortunately SharePoint gives you a quick and easy way of getting at all the user properties for Mr Boddy (or anyone else for that matter!): SPFieldUserValue. Tada! Create a new object of that type, give it the value you’ve read from the list field, and then point an SPUser object at it, hey presto, you’ve got everything you could want. This saves having to write your own parser, and if Microsoft change the format down the line, they should update this class in the process.

Here is some lovely (delete if appropriate) code to demonstrate. This code was written to return either login names or email addresses for a multi-user field, hence the foreach() loop:


public string GetUserListFromField(SPWeb web,
                 string fieldValue,
                 bool returnEmail)
{
    string returnValue = "";

    //get collection of users from passed-in value
    SPFieldUserValueCollection allUsers = new
      SPFieldUserValueCollection(web, fieldValue);

    foreach(SPFieldUserValue fieldUser
               in allUsers)
    {
        //convert value to user
        SPUser user = fieldUser.User;

        if (returnEmail)
        {
            //return email address if requested
            returnValue += user.Email + ";";
        }
        else
        {
            //return login names
            returnValue += user.LoginName + ";";
        }
    }

    //trim the trailing semicolon
    int i = returnValue.LastIndexOf(";");
    returnValue = returnValue.Substring(0, i);

    //tidy up
    web.Dispose();

    return returnValue;
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: