Tutorial :Adding SPFieldLookup to a list programmatically?


I added a SPFieldLookup field to a list programmatically.

When I checked my list view I found that the lookup field is as if I added it from the user inerface without specifying that it is linked to item.

Is there a method to force the lookupfield to be linked to item programmatically?


If you are provisioning both the list where the SPFieldLookup field is in, and the target list you will have a problem. Because the SPFieldLookup field needs to assign the target list by its GUID, which is created dynamically when the feature is activated. And you can't define this value in your field definition, since it doesn't exists yet.

The solution to this problem is provisioning both the "source" list and the target list normally, except the SPFieldLookup field in the source list.
Then, in the feature activated event, you add this lookup field programmatically, which could now be done since you have (or at least can find out) the GUID for the target list.


This is a nice snippet I saw and will like to share Let us assume we have two list aList and bList already created. Requirement is to create a lookup column in aList which will look up values in bList.

 SPList aList = web.Lists["aList"];   SPList bList = web.Lists["bList"];   aList.Fields.AddLookup("Lookup", bList.ID, false);   SPFieldLookup fldLookup = aList.Fields["Lookup"] as SPFieldLookup;   fldLookup.LookupField = bList.Fields[SPBuiltInFieldId.Title].InternalName;   fldLookup.Update();  


Did you fill all the needed properties (LookupField, LookupWebId and maybe also LookupList) and Update() the field afterwards?

Perhaps http://www.alexbruett.net/?p=153 will help

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Next Post »