Tuesday, June 19, 2012

Create SharePoint Lookup Field Programmatically


Lets see how to create a lookup field in a list programmatically

Lets you have a list named "Expense" and another list "Expense Category"

In the "Expense" list you want a lookup field from "Expense Category" list on "Expense Category" field

First add a lookup field named "Category" in the "Expense" list as

   SPList Expense = web.Lists.TryGetList("Expense");
   SPList ExpenseCategory = web.Lists.TryGetList("Expense Category");

   SPFieldCollection _fields = Expense.Fields;

   _fields.AddLookup("Category", ExpenseCategory.ID, true);

In above code i get the collection of fields from the "Expense" list and added a lookup field named "Category" and passed the

GUID of "Expense Category" list from lookup is to be set and set required to true.

Now get the recently created lookup field as

   SPFieldLookup Category = Expense.Fields["Category"] as SPFieldLookup;

Set the lookup field from the "Expense Category" list, Field "Expense Category" and update the field

   Category.LookupField = ExpenseCategory.Fields["Expense Category"].InternalName;


   Category.Update();


deploy the solution and verify the lookup field created in the list

1 comment:

  1. Can you create a lookup field that is filtered by values in other fields (i.e. on the same table where the lookup field is being created)?

    ReplyDelete