Domanda

I have a "person or group" type column in my calendar list as "Participants". I need to add and remove users from this column. Adding users works fine. When trying to remove a user it does not get removed. The code is:

SPListItem item = myList.GetItemById(itemId);
string usersOfItem = item["Participants"].ToString();
SPFieldUserValueCollection participants = new SPFieldUserValueCollection(web, usersOfItem);

//user login i get from a querystring
SPUser user = web.SiteUsers[login];
SPFieldUserValue userFUValue=new SPFieldUserValue(web, user.ID, user.Name);

// Below line executes with no error but user is not removed
participants.Remove(userFUValue);

item["Participants"] = participants;

item.Update();

I tried SPFieldUserValue userFUValue=new SPFieldUserValue(web, user.ID, user.LoginName); instead of user.Name but login name does not work as during debugging i see loginName gives the below value

i:0#.w|DOMAIN\fdixon

Which does not match with the user displayed in SPFieldUserValueCollection . The user inside the collection is displayed in the foramt : "ID;firstname lastname" Eg:

1;#Franklin Dixon

When SPFieldUserValue userFUValue=new SPFieldUserValue(web, user.ID, user.Name); is used, the two user field's matches, the code runs with no error. But user is not removed. . The user is available in the participants SPFieldUserValueCollection after Remove() is executed. Am i missing any point here ?

È stato utile?

Soluzione

Use following code:

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();
} 
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a sharepoint.stackexchange
scroll top