spfielduservaluecollection.remove not working
-
10-12-2019 - |
Question
I want to remove the user from the list item from the column of type person or group and it is multi-valued.
My code is:
private void DeleteUserFromList(SPUser userDeleted, string fieldName, SPListItem item, SPWeb sPWeb)
{
SPFieldUserValueCollection Users = item[fieldName] as SPFieldUserValueCollection;
SPFieldUserValue DeletedUserValue = new SPFieldUserValue(sPWeb, userDeleted.ID, userDeleted.LoginName);
Users.Remove(DeletedUserValue);
item[fieldName] = Users;
item.Update();
item.ParentList.Update();
}
When the code gets executed SPFieldUserValueCollection
values remain same after Remove()
i.e. If SPFieldUserValueCollection
fetches 2 users then they remain 2 after executing Remove() method.
What should I do?
Solution
Instead of creating a new SPFieldUserValue find the one in the SPFieldValueCollection you want to remove like this:
private static void DeleteUserFromList(SPUser userDeleted, string fieldName, SPListItem item, SPWeb sPWeb)
{
SPFieldUserValueCollection Users = (SPFieldUserValueCollection)item[fieldName];
SPFieldUserValue DeletedUserValue = Users.First(u => u.LookupId == userDeleted.ID);
Users.Remove(DeletedUserValue);
item[fieldName] = Users;
item.Update();
}
OTHER TIPS
Try the below code,
SPFieldUserValueCollection fuvc = item[fieldName] as SPFieldUserValueCollection;
foreach (SPFieldUserValue value in fuvc)
{
if (value.LookupId == userDeleted.ID)
{
fuvc.Remove(value);
item[fieldName] = fuvc;
item.Update();
break;
}
}
Hope this helps you.
Licensed under: CC-BY-SA with attribution
Not affiliated with sharepoint.stackexchange