Take the 2-minute tour ×
SharePoint Stack Exchange is a question and answer site for SharePoint enthusiasts. It's 100% free, no registration required.

I have a list which contains a field users (Multivalues are allowed so it can contain multiple users)

I would like to retrieve the email addresses of all users and assign them to a string? Anyone some help on how to achive this with code behind (c#) in SharePoint 2010?

share|improve this question

1 Answer 1

up vote 3 down vote accepted

Assuming your field is a user/group field with multiple selections, the below code should get you started. I adapted the code found at http://gemsolution.blogspot.com/2009/04/fun-with-spfielduservaluecollection.html to your specs.

 StringBuilder allEmails = new StringBuilder();
 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;
                     allEmails.Append(oUser.Email + ",");
                 }
             }
         }
     }

 }
 string allEmailsInAString = allEmails.ToString();
share|improve this answer
    
Exactly what I was looking for, Thanks Steve! –  Wim Hill Aug 31 '11 at 6:47

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.