I have been searching around to see the various ways in which people are retrieving Users and Groups objects or the string value from relevant SPField object when retrieving ListItems from a SharePoint List, and I have found that there are quite a few blog posts on this subject, all with differing code and views.
Having now tested nearly all of them, i have used 2 approaches that have helped me and the are
- Retreiving an SPUser or SPGroup object – perhaps for validation purposes or to gain other information about the user of group
- Retrieving a User friendly string representation of the User or Group – perhaps for simple display purposes.
The code below show the retrieval of the SPUser/SPGroup objects
Code Snippet
- using (SPSite site = new SPSite("http://mysite.com/sitecollection"))
- {
- using (SPWeb web = site.OpenWeb("mysitename"))
- {
- SPList oList = web.Lists["ListName"];
- SPListItemCollection oListItems = oList.Items;
- foreach (SPListItem oListItem in oListItems)
- {
- //Gets a collection of all the User and Group objects from the UserGroup Field
- SPFieldUserValueCollection oFieldUserValueCollection =
- new SPFieldUserValueCollection(web, oListItem["FieldName"].ToString());
- //Next, loop through the Values in the Collection
- foreach (SPFieldUserValue oFieldUserValue in oFieldUserValueCollection)
- {
- //now we need to test if the SPFieldUserValue is a
- //User or a Group, because if we simply assign a user
- //we will get a Null Reference Exception if it is a Group
- //It is a Group
- if (oFieldUserValue.User == null)
- {
- //Create and assign a new SPGroup object by using the
- //Lookup value to return a Group from the current Site(SPWeb)
- SPGroup oGroup = web.Groups.GetByID(oFieldUserValue.LookupId);
- }
- //It is a User
- else
- {
- //Create and assign a new SPUSer object by using the User
- //property of the SPFieldUserValue object
- SPUser oUser = oFieldUserValue.User;
- }
- }
- }
- }
- }
and the code below here shows the retrieval if the simple string representation.
Code Snippet
- SPList oList = web.Lists["ListName"];
- SPListItemCollection oListItems = oList.Items;
- foreach(SPListItem oListItem in oListItems)
- {
- SPFieldUserValueCollection oFieldUserValueCollection
- = SPFieldUserValueCollection(web, oListItem["FieldName"].ToString());
- foreach(SPFieldUserValue oFieldUserValue in oFieldUserValueCollection)
- {
- //simply retrieve the string value from the SPFieldUserValue object
- string sFieldValue = oFieldUserValue.LookupValue;
- }
- }
If anyone else has any more thoughts on this please let us know.
Your blog is very useful..!!
ReplyDeleteThanks for your post!
ReplyDelete