1

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?

3

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();
} 
2

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.