Programmatically Adding to and Removing from a Person or Group Column
2010-07-13 09:49
375 查看
Using the UI, it is quite easy to add and remove users. (Note: You must make sure the column allows multiple selections to add more than one user). But how would this be done programmatically using the SharePoint Object Model? This is a bit more complex since we somehow need to add or remove items from a list (e.g. both Robert King and Laura Callahan). And this list is stored in a single field’s value.
The answer is to use a class called SPFieldUserValueCollection. As you’ll guess, it’s a collection of SPFieldUserValue objects, and each SPFieldUserValue object basically represents a single user (SPUser) or group (SPGroup) from your site collection.
Here’s some code to help explain what I mean. This code retrieves a single item from the Tasks list and iterates through each field user value.
//Get a handle to our Tasks list
SPList tasks = web.Lists["Tasks"];
//Select first in the list
SPListItem task = tasks.Items[0];
//Access value from AssignedTo and cast to SPFieldUserValueCollection
SPFieldUserValueCollection AssignedTo = (SPFieldUserValueCollection)task["AssignedTo"];
foreach (SPFieldUserValue fuv in AssignedTo)
{
Console.WriteLine("LookupId = {0}, LookupValue = {1}", fuv.LookupId, fuv.LookupValue);
}
foreach (SPFieldUserValue Value in Values)
{
if (User != null)
{
SPUser User = Value.User;
Users.Add(User);
}
else
{
SPGroup Group = Web.Groups.GetByID(Value.LookupId);
Groups.Add(Group);
Users.AddRange(Group.Users);
}
}
This results in the following console output for the single task shown above:
LookupId = 19, LookupValue = Robert King
LookupId = 16, LookupValue = Laura Callahan
For those curious, you can also take the value of the field and output as a string using syntax like: task[“AssignedTo”].ToString(). If you do, it will look like this:
19;#Robert King;#16;#Laura Callahan
(Note: this is the same way that a Lookup column works. See this well-written blog article for more info on this.)
So, you should have a basic idea on how this is internally stored within SharePoint. Let’s now get to the code which actually adds or remove users. To do this, I wrote two simple helper methods that you’re welcome to use. Here is the one that adds a user or group:
void AddPrincipal (SPListItem item, string column, SPPrincipal principal)
{
SPFieldUserValueCollection fuvc = (SPFieldUserValueCollection)item[column];
fuvc.Add(new SPFieldUserValue(item.ParentList.ParentWeb, principal.ID, principal.Name));
item[column] = fuvc;
item.Update();
}
It’s pretty straight forward. The reason I called the method AddPrincipal is that SPPrincipal is the base class for SPUser and SPGroup. This allows it to be used for either object type. The method takes the SPListItem, the name of the column and the SPPrincipal. Here’s how we would call it from our code:
SPUser user = web.SiteUsers["synergy\\lcallahan"];
AddPrincipal(task, "AssignedTo", user);
Calling it to add a group is the same. Here is an example:
SPGroup group = web.SiteGroups["Home Owners"];
AddPrincipal(task, "AssignedTo", group);
Removing is a little trickier as we must first find the SPPrincipal. Here is the code:
void RemovePrincipal(SPListItem item, string column, SPPrincipal principal)
{
SPFieldUserValueCollection fuvc = (SPFieldUserValueCollection)item[column];
foreach (SPFieldUserValue value in fuvc)
{
if (value.LookupId == principal.ID)
{
fuvc.Remove(value);
item[column] = fuvc;
item.Update();
break;
}
//optionally throw an exception if not found
//throw new System.ArgumentException ("Principal not found");
}
}
Calling into the method is very simple. Here we are removing a user and a group.
RemovePrincipal(task, "AssignedTo", user);
RemovePrincipal(task, "AssignedTo", group);
The answer is to use a class called SPFieldUserValueCollection. As you’ll guess, it’s a collection of SPFieldUserValue objects, and each SPFieldUserValue object basically represents a single user (SPUser) or group (SPGroup) from your site collection.
Here’s some code to help explain what I mean. This code retrieves a single item from the Tasks list and iterates through each field user value.
//Get a handle to our Tasks list
SPList tasks = web.Lists["Tasks"];
//Select first in the list
SPListItem task = tasks.Items[0];
//Access value from AssignedTo and cast to SPFieldUserValueCollection
SPFieldUserValueCollection AssignedTo = (SPFieldUserValueCollection)task["AssignedTo"];
foreach (SPFieldUserValue fuv in AssignedTo)
{
Console.WriteLine("LookupId = {0}, LookupValue = {1}", fuv.LookupId, fuv.LookupValue);
}
foreach (SPFieldUserValue Value in Values)
{
if (User != null)
{
SPUser User = Value.User;
Users.Add(User);
}
else
{
SPGroup Group = Web.Groups.GetByID(Value.LookupId);
Groups.Add(Group);
Users.AddRange(Group.Users);
}
}
This results in the following console output for the single task shown above:
LookupId = 19, LookupValue = Robert King
LookupId = 16, LookupValue = Laura Callahan
For those curious, you can also take the value of the field and output as a string using syntax like: task[“AssignedTo”].ToString(). If you do, it will look like this:
19;#Robert King;#16;#Laura Callahan
(Note: this is the same way that a Lookup column works. See this well-written blog article for more info on this.)
So, you should have a basic idea on how this is internally stored within SharePoint. Let’s now get to the code which actually adds or remove users. To do this, I wrote two simple helper methods that you’re welcome to use. Here is the one that adds a user or group:
void AddPrincipal (SPListItem item, string column, SPPrincipal principal)
{
SPFieldUserValueCollection fuvc = (SPFieldUserValueCollection)item[column];
fuvc.Add(new SPFieldUserValue(item.ParentList.ParentWeb, principal.ID, principal.Name));
item[column] = fuvc;
item.Update();
}
It’s pretty straight forward. The reason I called the method AddPrincipal is that SPPrincipal is the base class for SPUser and SPGroup. This allows it to be used for either object type. The method takes the SPListItem, the name of the column and the SPPrincipal. Here’s how we would call it from our code:
SPUser user = web.SiteUsers["synergy\\lcallahan"];
AddPrincipal(task, "AssignedTo", user);
Calling it to add a group is the same. Here is an example:
SPGroup group = web.SiteGroups["Home Owners"];
AddPrincipal(task, "AssignedTo", group);
Removing is a little trickier as we must first find the SPPrincipal. Here is the code:
void RemovePrincipal(SPListItem item, string column, SPPrincipal principal)
{
SPFieldUserValueCollection fuvc = (SPFieldUserValueCollection)item[column];
foreach (SPFieldUserValue value in fuvc)
{
if (value.LookupId == principal.ID)
{
fuvc.Remove(value);
item[column] = fuvc;
item.Update();
break;
}
//optionally throw an exception if not found
//throw new System.ArgumentException ("Principal not found");
}
}
Calling into the method is very simple. Here we are removing a user and a group.
RemovePrincipal(task, "AssignedTo", user);
RemovePrincipal(task, "AssignedTo", group);
相关文章推荐
- mysql query to find the maximum 3 values from a column and group by on other column
- How to read one column from SQLite and store in Array
- Configure file like format of ini and read data from ini file or write data to ini file
- radgrid column filter, filtered by a “From” and “To” date, inclusive
- Filtering by a group in a SharePoint Person or Group column
- Adding new storage disks and Dropping old storage disks from OCR ,Vote diskgroup
- VMware - support Cut, Copy, or Paste to and from VM's
- trim content between begin and end lines or get from keyword line to file end
- How to get value of the person or group type via CAML Query js
- 【RAC搭建报错】You need disks from at least two different failure groups, excluding quorum disks and quorum failure groups, to create a Disk Group with normal redundancy
- (add comment to table or column,and add comment to ddl script) erwin为ddl script 脚本添加表或字段的注释(导出注释)(comment)
- Steps To Migrate-Move a Database From Non-ASM to ASM And Vice-Versa
- How to build and run ARM Linux on QEMU from scratch
- SQL-Server collation, what is it and how to change db/column collation
- poj2762 Going from u to v or from v to u?
- 车辆检测“Deep MANTA: A Coarse-to-fine Many-Task Network for joint 2D and 3D vehicle analysis from monoc”
- Export GridView with Images from database to Word Excel and PDF Formats
- This event supports the .NET Framework infrastructure and is not intended to be used directly from your code?继承自VScrollbar的自定义winform控件,某些事件不触发的问题(Winform控件开发学习)
- Calling Fortran function and subroutines from a C or C++ function
- pku2762(Going from u to v or from v to u?)