SharePoint Blog - René Hézser

Anmelden  RSS Feed RSS Feed
Startet die Suche

Archive

Kategorien

Links

Andere Blogs




ITaCS GmbH


Write a SPFieldUser  

Apr 162007

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.

 
Posted by René Hézser | 6  Comments | Trackback Url  | 0  Links to this post | Bookmark this post with:        
Tags: Development, SharePoint, SPField
Technorati Tags: , ,

Links to this post

Comments

commented on  Friday, March 27, 2009  3:46 PM  by  Michael Martin
Nice tip. Thks !

commented on  Monday, June 08, 2009  9:18 PM  by  Andy N.
Thanks a lot ! Saved my day :-)

commented on  Friday, August 14, 2009  1:14 PM  by  Rick
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

commented on  Friday, August 14, 2009  10:03 PM  by  René Hézser
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é

commented on  Thursday, January 26, 2012  5:31 PM  by  Christian Buntrock
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

commented on  Thursday, January 26, 2012  5:40 PM  by  Christian Buntrock
Damn, forget about it. Error in front of Keyboard...

Name *:
URL:
Email:
Kommentar:


CAPTCHA Image Validation