Using the PeoplePicker in your custom webpart
In my current project I wanted to create a webpart where I could add users to a certain group in a site from a single adminstration site. Furthermore I wanted to use the nice and elegant People Picker. This control is called “PeopleEditor” which belongs to the Microsoft.SharePoint.WebControls namespace. This is how it looks like when ran in a webpart :
Here is the code to get the values from the control :
PeopleEditor _peoplePicker = new PeopleEditor();
_peoplePicker.AllowTypeIn = true;
_peoplePicker.AllowEmpty = false;
_peoplePicker.MultiSelect = false;
SPWeb web = new SPSite("urlToWeb").OpenWeb();
SPGroup group = web.SiteGroups["groupname"];
web.AllowUnsafeUpdates = true;
if (Group.Users.Count > 0)
{
SPUserCollection users = group.Users;
foreach (SPUser user in users)
{
group.Users.Remove(user.LoginName);
group.Update();
}
}
try
{
group.AddUser(_peoplePicker.Accounts[0].ToString(), "", "", "");
group.Update();
}
catch (ArgumentException error)
{
//Do ErrorHandling here
}
finally
{
web.AllowUnsafeUpdates = false;
web.Close();
web.Dispose();
}
And here is the code to set the values from the control :
if (group.Users.Count > 0)
{
foreach (SPUser user in group.Users)
{
_peoplePicker.CommaSeparatedAccounts= user.LoginName;
}
}
Took me a couple of hours to find out I had to use the CommaSeperatedAccount property. Since you are getting the values using the Accounts or the Entities properties, it seems a bit odd to use this method to set the values.
5 Comments |
Posted
Tuesday, 17 Jun 2008 02:57
by
Robin Meure
in
Code