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();                 
Guruparan Giritharan
  • 15,660
  • 4
  • 27
  • 50
  • This also Helpful [Get and Set a SharePoint Lookup Field Values Using SSOM C#](https://social.technet.microsoft.com/wiki/contents/articles/40271.get-and-set-a-sharepoint-lookup-field-values-using-ssom-c.aspx) – Mohamed Oct 22 '17 at 09:37

1 Answers1

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(); 
Spontifixus
  • 6,570
  • 9
  • 45
  • 63
  • 1
    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. – xr280xr Jan 18 '13 at 19:40
  • @xr280xr, huh, interesting. [MSDN states](http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.splistitem(v=office.12).aspx) 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? – Spontifixus Jan 23 '13 at 08:30
  • 1
    I had the impression that it was `;#` and not `:#` for the separator. Am I missing something? – user2173353 May 20 '15 at 14:57