Tag Archives: SPFIeldUserValue

SharePoint User Field – Getting user objects (multiple and single)

I needed to get the users stored in a user field in two lists. In one list, multiple users were stored in each item, in the other list, only one user per item. I found a couple of blog and forum posts which really helped me out. This is my solution based on theirs. Link to the source posts are at the bottom of this post.

Both Solutions presume you have already gotten your SPWeb stored in a variable called “web”.

Getting single user from user field:

SPList list = web.Lists["MyList"];
foreach (SPListItem item in list.Items)
{
	string fieldValue = item["NameOfUserField"].ToString();
	SPFieldUserValue userValue = new SPFieldUserValue(web, fieldValue);
	SPUser user = userValue.User;
	//Do something with user
}

Getting multiple users from user field:

SPList list = web.Lists["MyList"];
foreach (SPListItem item in list.Items)
{
	string fieldValue = item["NameOfUserField"].ToString();
	SPFieldUserValueCollection users = new SPFieldUserValueCollection(web, fieldValue);

	foreach (SPFieldUserValue userValue in users)
	{
		SPUser user = userValue.User;
		//Do something with user
	}
}

NOTE: If there is a possibility that the field doesn’t contain any users you need to handle it, or a null reference error will occur. Just wrap the code in an “if(item[“NameOfUserField”] != null)” statement.

Here are the sources:

Another simple code snippet – using the user field

How best to convert a SharePoint multi-user field string into an array of SPUsers?

Advertisements