2

I am trying to remove a user from my SPFieldUserValueCollection but I keep get the error

'SPFieldUserValue' does not contain a definition for 'Add' and no extension method 'Add' accepting a first argument of type 'SPFieldUserValue'

Here is my code

spWeb.AllowUnsafeUpdates = true;
string variable1 = Page.Request.QueryString["myID"];
int ListItemId = Int32.Parse(variable1);
SPUser userDeleted = SPContext.Current.Web.CurrentUser;
SPList List = spWeb.Lists["BGAG Learning Calendar"];
SPListItem ListItem = List.GetItemById(ListItemId);
SPFieldUserValueCollection FieldUserValueCollection = (SPFieldUserValueCollection)ListItem["Course Attendies"];
SPFieldUserValueCollection fieldUserValues = new SPFieldUserValueCollection();

foreach (SPFieldUserValue fieldUserValues1 in FieldUserValueCollection)
{
       if (fieldUserValues1.LookupId != userDeleted.ID && fieldUserValues1.LookupValue != userDeleted.Name)
       {
             fieldUserValues1.Add(new SPFieldUserValue(spWeb, fieldUserValues1.LookupId, fieldUserValues1.LookupValue));
       }
}
ListItem["Course Attendies"] = fieldUserValues;
ListItem.Update();
spWeb.AllowUnsafeUpdates = false;
3

Your problem is that you are referencing the wrong variable when you try to add your SPFieldUserValue.

Look closely at your code. You create a SPFieldUserValueCollection called "fieldUserValues". You then iterate through another collection, and inside the foreach, the single SPFieldUserValue you are working with is called "fieldUserValues1".

Notice that that is nearly identical to the empty collection you created, except it has a "1" on the end.

Now look at the line of code where you are trying to add to the collection.

You are trying to add to "fieldUserValues1". In other words, you are trying to add a new SPFieldUserValue into a single SPFieldUserValue, not into a SPFieldUserValueCollection.

You need to change that line of code to be

fieldUserValues.Add(new SPFieldUserValue(spWeb, fieldUserValues1.LookupId, fieldUserValues1.LookupValue));
3

Should you not call Add on fieldUserValues and not fieldUserValues1 ( that is a SPFieldUserValue, not a SPFieldUserValueCollection)?

Like

foreach (SPFieldUserValue fieldUserValues1 in FieldUserValueCollection)
{
       if (fieldUserValues1.LookupId != userDeleted.ID && fieldUserValues1.LookupValue != userDeleted.Name)
       {
             fieldUserValues.Add(new SPFieldUserValue(spWeb, fieldUserValues1.LookupId, fieldUserValues1.LookupValue));
       }
}

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.