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();
In the list where you want the Lookup column, select Add column > Lookup. Under Select list as a source, select the source list to get information from. Under Select a column from the list above, select what information you want to display from the source list in this new column in the target list.
To update lookup field value in SharePoint Online, use Values @{“Lookup” = “1”}, where the “1” is the ID of the parent lookup item. Here “3” is the ID of the parent lookup item. Similarly, to update a multi-valued lookup field, just specify the IDs of parent lookup items comma separated.
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With