Tuesday, September 27, 2011

Adding a lookup field to a list programatically

Alright, I had a requirement where a lookup field needs to be added to list referencing another list's ID column. I managed to do this using the below code. You can understand without explaining all the inner details, I think.

//Adding a lookup column to link the item to the related item
var list = web.Lists["LookupListName"];
thisList.Fields.AddLookup("LookupFieldName", list.ID , web.ID, true);
SPFieldLookup lookupField = reportThisList.Fields.GetField("LookupFieldName" 
                                 as SPFieldLookup;
lookupField.LookupField = "ID";
//Adding indexing to enable "CACADE" delete of this list items
lookupField.Indexed = true;
//CASCADE - deletes all the related items in this list when an item is deleted.
lookupField.RelationshipDeleteBehavior = SPRelationshipDeleteBehavior.Cascade;
lookupField.Update(true);

After doing this above code, you will see a new column in the list (thisList). Here is a preview












If an item is deleted from the related list("LookupListName"), all the related items in thisList would get deleted automatically.

I know this might not give you a clear explanation. If you need more details, just add a comment, I will try to explain it in more detail.

Thanks
Senthil S

No comments:

Post a Comment