Witcher
Witcher

Reputation: 1140

Create lookup field in SharePoint 2010

How to add lookup column in List1 and bind it with SomeField from List2, and then fill this lookup column with plain text (only use code)?

Upvotes: 0

Views: 1707

Answers (1)

Rob Windsor
Rob Windsor

Reputation: 6859

Here's the code to create a lookup field:

var list = web.Lists["List1"];    
var targetList = web.Lists["List2"];
var fieldName = list.Fields.AddLookup("My Lookup", targetList.ID, false);
var field = list.Fields.GetFieldByInternalName(fieldName) as SPFieldLookup;
field.LookupField = "SomeField";
field.Update();

To update the lookup field you set it to the item ID of the item in the target list.

Upvotes: 5

Related Questions