Ads

Thursday, 4 April 2013

understand the use of SPFieldUserValue and SPFieldUserValueCollection

Most of the time we have seen that people are using people and group field, and for fetching that field they are just using string manipulation for taking login name or name.
And that is totally wrong.

So here is simple code snippet for how to fetch user from SharePoint list.
To do this you have to use SPFieldUserValue object provided by SharePoint object model
Here is the start up
SPSite site = new SPSite("http://spvm");
SPWeb web = site.OpenWeb();
SPList list = web.Lists["DemoList"];
SPListItem item = list.GetItemById[1];
SPFieldUserValue objUserFieldValue = new SPFieldUserValue(web, item["User"].ToString());

Once you get this object SPFieldUserValue ( objUserFieldValue) then you can retrieve each and every property of that user by following way.

objUserFieldValue.User.LoginName;
objUserFieldValue.User.Name;
objUserFieldValue.User.ID;
objUserFieldValue.User.Groups;
objUserFieldValue.User.Roles;
objUserFieldValue.User.Email;
objUserFieldValue.User.Sid;
objUserFieldValue.User.UserToken;

So all the properties of SPUser will be available and you can use that the same way you treat SPUser field.

For group you can like this way

If(objUserFieldValue.User==null)
//Then selected value is group.
Else
//Selected value is user.

For allowing multi selection we have to use collection
SPFieldUserValueCollection objUserFieldValueCol = new SPFieldUserValue(web, item["User"].ToString());
for (int i = 0; i < objUserFieldValueCol.Count; i++)
{
SPFieldUserValue singlevalue = objUserFieldValueCol[i];
if (singlevalue.User == null)
//then single value is group
else
//singlevalue is user and you can use all SPUser properties.
}

This is same concept as SPLookupFieldvalue and this is also good practice to imbibe.

No comments:

Post a Comment

Ads