Tuesday, April 21, 2009

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.


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

//Then selected value is group.
//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
//singlevalue is user and you can use all SPUser properties.

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


pals said...

In which .net application to write the code of getting username?????
pls tel in detail...

SharePoint Kings said...

you can write this code to any webpart, in event handler, in feature receiver or any where you want this detail.

The Real Leo said...

I had a scenario in which I used this. Thanks a ton!!! :)

The Real Leo said...

I had a scenario in which this explanation was extremely helpful!
Thanks a ton!!! :)

Share your SharePoint Experiences with us...
As good as the SharePointKings is, we want to make it even better. One of our most valuable sources of input for our Blog Posts comes from ever enthusiastic Visitors/Readers. We welcome every Visitor/Reader to contribute their experiences with SharePoint. It may be in the form of a code stub, snippet, any tips and trick or any crazy thing you have tried with SharePoint.
Send your Articles to sharepointkings@gmail.com with your Profile Summary. We will Post them. The idea is to act as a bridge between you Readers!!!

If anyone would like to have their advertisement posted on this blog, please send us the requirement details to sharepointkings@gmail.com