How to add a value to a lookup field in sharepoint?
Asked Answered
B

1

6

Hi I have two Lists in sharepoint 2007. I have a lookup column in on list which looks the other field. I want to use the sharepoint object model to add an item to the second list. How to i set the lookup field value. (The value is already in the other list).?

SPListItem Employee = web.Lists["Employee"].Items.Add();
Employee["Name"] = account.Name;
Employee["Department"] = <lookup value must come here>
Employee.Update();                 
Battement answered 24/9, 2012 at 7:53 Comment(1)
This also Helpful Get and Set a SharePoint Lookup Field Values Using SSOM C#Caviness
H
5

Lookup fields will contain a combination of the row's id and the value of the column to display, separated by :#, in your case that could be 1:#HumanResources or 12:#Engineering.

So to reference a lookup simply setting the id won't be enough, instead the above mentioned string needs to be set. Luckily SharePoint provides the class SPFieldLookupValue that does exactly this:

var department = web.Lists["Department"].GetItemById(1);
var employee = web.Lists["Employee"].Items.Add();
employee["Name"] = account.Name;
employee["Department"] = new SPFieldLookupValue(department.ID, department.Title);
employee.Update(); 
Harbin answered 24/9, 2012 at 9:34 Comment(3)
This doesn't appear to be necessary. If I check the value of employee["Department"] after setting it, it is simply set to "1". And if I just do employee["Department"] = "1"; employee.Update(); it works fine.Sayles
@xr280xr, huh, interesting. MSDN states that "A Lookup field contains a string in the form ID;#VALUE, where ID is the list item ID and VALUE is the value of the lookup field in the other list." Are you sure that the item in the other List is being referenced correctly, when doing it your way?Harbin
I had the impression that it was ;# and not :# for the separator. Am I missing something?Jeunesse

© 2022 - 2024 — McMap. All rights reserved.