1

I want to add values to a lookupmulti field with c#. the form shows the field correctly but my code just won't work:

SPList list = SPContext.Current.Web.Lists["testlist"];
SPListItem item = list.GetItemById(someId);
SPFieldLookupValueCollection fieldValues = new SPFieldLookupValueCollection();
foreach(int id in itemIds) {
   fieldValues.Add(new SPFieldLookupValue {LookupId = id});
}
item["lookupmultifield"] = fieldValues;

The code above is not exactly my code, but it's how i thought it should work. FieldValues has 2 entries, but only the first is inserted in the lookupmulti field. can anyone help?

3 Answers 3

6

here's a code fragment that's similar but 'list.Items.Add() & item.Update()' are missing from your code

SPList list = SPContext.Current.Web.Lists["testlist"];  
SPListItem item = list.Items.Add();  
SPFieldLookupValueCollection fieldValues = new
SPFieldLookupValueCollection();

fieldValues.Add (new SPFieldLookupValue(1, "SomeValue1"));  // add other field values or in loop

item["lookupmultiField"] = fieldValues;
item.Update();  
2
  • thanks, but i updated some other fields and updated after that.
    – domueni
    Feb 20, 2012 at 8:00
  • Any Example with Linq?
    – tola
    Jul 6, 2015 at 10:16
0

I'm not sure, but there are 2 constructors for SPFieldLookupValue class:

SPFieldLookupValue(String) // Initializes a new instance of the SPFieldLookupValue class that is based on the specified field value.
SPFieldLookupValue(Int32, String) // Initializes a new instance of the SPFieldLookupValue class that is based on the specified lookup identifier (ID) and value.

It looks like you should specify Id and Value of related objects...

3
  • thanks but I tried that already but same result
    – domueni
    Feb 16, 2012 at 14:20
  • will post the solution when i can
    – domueni
    Feb 16, 2012 at 14:24
  • Are you sure that you use correct Value? '<Field ID="x" Type="Lookup" List="x" ShowField="Title"...' you should use value of field that is set in ShowField property of list schema. In example above it is Item["Title"]
    – Alexander
    Feb 16, 2012 at 14:37
0

i wrote Mult="True" instead of Mult="TRUE"

I should not listen to VS 2010 intellisense

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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