add a lookup column and set relationship behaviour for Sharepoint 2010 list

This post is a short example for how to add a lookup column and set the relationship behaviour for the lookup column using sharePoint 2010 object model

The demo code was created in a console applictaion

SPList SourceList = lists[SourceListId]; -> List.ID of your Source or lookup list
SPList TargetList = lists[TargetListId]; -> List.ID of your list that will contain lookup column

SPFieldCollection Fields = TargetList.Fields;

//Adding a lookup Field in Child List
Fields.AddLookup(lookupFieldName, SourceList.ID, true);
Console.WriteLine("Lookup Field Created");

//Adding the Restrict behaviour
SPFieldLookup NewLookupField = Fields[lookupFieldName] as SPFieldLookup;
NewLookupField.Indexed = true;
NewLookupField.LookupField = "Title";
NewLookupField.RelationshipDeleteBehavior = SPRelationshipDeleteBehavior.Restrict;

Thats it!


Post a Comment


This is a personal weblog. The opinions expressed here represent my own and not those of my employer or anyone else. Should you have any questions or concerns please e-mail me at .

Copyright (c) 2010 @ All rights are reserved.Do Not Copy.

@ Learning