Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add a value to a lookup field in sharepoint?

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();                 
like image 977
Guruparan Giritharan Avatar asked Sep 24 '12 07:09

Guruparan Giritharan


People also ask

How do I use a lookup column in a SharePoint list?

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.

How do I update a lookup field in SharePoint powershell?

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.


1 Answers

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(); 
like image 199
Spontifixus Avatar answered Oct 04 '22 00:10

Spontifixus