Navigation

Sunday, 1 February 2015

Add/Remove current user in ‘person and group’ field in SharePoint list Programmatically

Use class called SPFieldUserValueCollection to Add/Remove current user in ‘person and group’ field in SharePoint list Programmatically.  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 Listitem from the “ListName” list and get “FieldName” person & group field user value. Then Append current user in this field.
using(SPSite site = new SPSite("sitecollectionurl"))
{
int ListItemId = 1;
SPWeb web = site.OpenWeb();
web.AllowUnsafeUpdates = true;
SPUser CurrentUser = web.CurrentUser;
SPList List = web.Lists[“ListName”];
SPListItem ListItem = List.GetItemById(ListItemId);
SPFieldUserValueCollection FieldUserValueCollection = (SPFieldUserValueCollection) ListItem[“FieldName”];
SPFieldUserValueCollection fieldUserValues = new SPFieldUserValueCollection();
if (FieldUserValueCollection!=null)
{
foreach (SPFieldUserValue FieldUserValue in FieldUserValueCollection)
{
fieldUserValues.Add(new SPFieldUserValue(web, FieldUserValue.LookupId, FieldUserValue.LookupValue));
}
}
fieldUserValues.Add(new SPFieldUserValue(web, CurrentUser.ID,CurrentUser.Name));
ListItem[“FieldName”] = fieldUserValues;
ListItem.Update();
web.AllowUnsafeUpdates = false;
}
below are some code to explain how to remove current user from person and group field in share point list. This code retrieves a single Listitem from the “ListName” list and get “FieldName” person & group field user value. Then remove current user in this field.
using(SPSite site = new SPSite(“sitecollectionurl"))
{
int ListItemId = 1;
SPWeb web = site.OpenWeb();
web.AllowUnsafeUpdates = true;
SPUser CurrentUser = web.CurrentUser;
SPList List = web.Lists[“ListName”];
SPListItem ListItem = List.GetItemById(ListItemId);
SPFieldUserValueCollection FieldUserValueCollection = (SPFieldUserValueCollection) ListItem[“FieldName”];
SPFieldUserValueCollection fieldUserValues = new SPFieldUserValueCollection();
foreach (SPFieldUserValue fieldUserValues in FieldUserValueCollection)
{
if (fieldUserValues.LookupId != CurrentUser.ID && fieldUserValues.LookupValue != CurrentUser.Name)
{
fieldUserValues.Add(new SPFieldUserValue(web, fieldUserValues.LookupId, fieldUserValues.LookupValue));
}
}
ListItem[“FieldName”] = fieldUserValues;
ListItem.Update();
web.AllowUnsafeUpdates = false;
}