Write a SPFieldUser

Write a SPFieldUser

If you have a list which contains a SPFieldUser field (with multiple selection), you can add users too it with the following code:

using (SPSite site = new
SPSite("http://site"))

{

using (SPWeb web = site.AllWebs["Web"])

    {

    SPList list = web.Lists["List"];

    SPListItem item = list.Items[0];

    SPFieldUserValueCollection values = (SPFieldUserValueCollection)item["Users"];

    SPUserCollection users = web.AllUsers;

    foreach (SPUser user in users)

    {

        values.Add(new
SPFieldUserValue(web, user.ID, user.Name));

    }

    item["Users"] = values;

    item.Update();

    }

}

In this example the list "List" would contain a field with the name "Users", which takes users. All web users are added to the field "Users" of the first list item, which is then updated.

6 Comments

Michael Martin

Reply

Nice tip. Thks !

 

Andy N.

Reply

Thanks a lot ! Saved my day 🙂

 

Rick

Reply

Rene, I’m looking to associate an event receiver for anytime a user or group is added to a sharepoint site within the collection. I’m familiar with how to write event receivers but all attempts have failed to capture the event associated with group creation or users added via the people picker. Many thanks in advance for your help!

btw, great tip above – I’ve recently used this logic on a customer site – many thanks for the contribution!

Rick

 

René Hézser

Reply

Hi Rick,
I think you would need to read the user form the picker, and check if it is new (if new means something has not been done for the user).
René

 

Christian Buntrock

Reply

Hi,

thank you very much for that information. Actually, when I try to access the values-Collection I’m getting a NullReference-Exception. 🙁

Regards
Christian

 

Christian Buntrock

Reply

Damn, forget about it. Error in front of Keyboard…

 

Leave a Reply