SharePoint Tip #18: Reading from and Writing to a User or Group column

Each field type has a different way to be read from and written to. The most used ones (single line of text, multiple lines of text, number, currency, date and time and yes/no) are easy to use because SharePoint's object model makes it very simple to set its value:

item["MyTextField"] = "My Text Value";

However, some of the field types store more than one value and, for that reason, must be handled differently. That is the case with the Person or Group field type (SPFieldUser class) which stores two values: the User ID and the User Login Name. The User ID is and integer number that SharePoint associates with each user (kind of like the ID that is generated for each item of a list), and User Login Name is something like Domain\UserName.

Since you must set both these values in a single column, SharePoint's API includes a special class, SPFieldUserValue, which allows you to do so. The following example shows how it's used:

SPWeb web = SPContext.Current.Web;
int userId = web.CurrentUser.ID;
String username = web.CurrentUser.LoginName;

item["MyUserField"] = new SPFieldUserValue(web, userId, username);

If you try to read the value of such a field, you will get something like 4;#MyDomain\AndreVala in which 4 is the User ID and MyDomain\AndreVala is the user's Login Name.