Revisiting the People Picker (PeopleEditor) Control


I was working with the People Editor Control and realized there are a couple weird things you need to do before you can read values into the control and save values into a list.  Here are a few samples related to saving multiple items into a list and reading multiple items from a list into the control.
Updating an Item from a PeopleEditor Control:
string[] UsersSeperated = peUserEditor.CommaSeparatedAccounts.Split(',');
                    SPFieldUserValueCollection UserCollection= new SPFieldUserValueCollection();
                    foreach (string UserSeperated in UserSeperated)
                    {
                        SPUser User = Web.SiteUsers[“UserField”];
                        SPFieldUserValue UserName = new SPFieldUserValue(Web, User.ID, User.LoginName);
                        UserCollection.Add(UserName);
                    }
Item["UserField"] = UserCollection
Notice that we have to separate the users, because it is comma delimited.  You have to split the string, then you cast the string in an SPUser, so that you can get theUser Guid and User Login for and SPFieldUserValue and add it to theSPFieldUserValue Collection.  My field is a People and Groups field, so it requires an SPFieldUserValueCollection.
Reading an SPFieldUserValueCollection into a PeopleEditor Control:
SPFieldUserValueCollection Users = new SPFieldUserValueCollection(Web, Item["UserField"].ToString());
                    string UsersCommaDelimited = "";
                    foreach (SPFieldUserValue User in Users)
                    {
                        if (UsersCommaDelimited == "")
                            UsersCommaDelimited = User.User.LoginName;
                        else
                            UsersCommaDelimited += "," + User.User.LoginName;
                    }
peUserEditor.CommaSeparatedAccounts = UsersCommaDelimited;
In this piece of code notice that we pull the value into anSPFieldUserValueCollection, then we loop through the login name and add them to a string using commas.  Then we can go ahead and save the string into the PeopleEditor’s CommaSeperatedAccounts Function for displaying on a form.
This control is incredibly simple to use, obviously you would not need to loop through and add the commas if you set the MultiSelect value to false.  It is a little different for multiple users, so I chose to write about that instead of adding a single user value.  If anyone has comments or questions let me know.  Later guys.

Comments

Popular posts from this blog

IRM and the Object Model

This content database has a schema version which is not supported in this farm

Activate and Deactivate Feature through PowerShell