Prasad Bolla's SharePoint Blog

Click Here to go through the Interesting posts within my Blog.

Click Here to go through the new posts in my blog.

Monday, November 28, 2011

Programmatically Create Relation between Sharepoint 2010 lists

In this we will create two lists in SharePoint 2010 and setup the Relation between the lists by adding the lookup column. Please note that the belwo example is a console application.

string lookupFieldName = “RelatedField”;

using (SPSite site = new SPSite(“http://SpSite”))
{
using (SPWeb web = site.OpenWeb())
{
SPListCollection lists = web.Lists;
//Creating Parent list
Guid SourceListId = lists.Add(“Parent List”,”", SPListTemplateType.GenericList);
Console.WriteLine(“Parent List Done…”);

//Creating Child List
Guid TargetListId = lists.Add(“Child List”,”",SPListTemplateType.GenericList);
Console.WriteLine(“Child List Done…”);

SPList SourceList = lists[SourceListId];
SPList TargetList = lists[TargetListId];

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;
NewLookupField.Update();
Console.WriteLine(“Lookup field integrity enforced”);

//Adding Items in the List
SPListItem NewSourceItem = SourceList.Items.Add();
NewSourceItem["Title"] = “Parent Data”;
NewSourceItem.Update();
Console.WriteLine(“Source listitem created”);

SPListItem NewTargetItem = TargetList.Items.Add();
NewTargetItem["Title"] = “Child Data”;
NewTargetItem[lookupFieldName] = new SPFieldLookupValue(1, “Source Data”);
NewTargetItem.Update();
Console.WriteLine(“Parent listitem created”);
TargetList.Update();
SourceList.Update();
}
}

No comments:

Post a Comment