I am developing a solution which has multiple OOTB lists like Links, Contacts, Custom List and Document Library.

And, I have to create a lookup field in four lists which refer to a field in a Custom Library.

Online, I saw many people having difficulty while setting the lookup field declaratively in the schema.xml file of the list. like:

Field Type="Lookup"
         DisplayName="Test field"
         Name="TestField" />

But, as the GUID to the list is assigned on instance creation, they were having problems.

Now, I am creating the Lookups for the list through code on an event, like:

newList.Fields.AddLookup("Lookup Column", targetList.ID, false);
SPFieldLookup lkp = (SPFieldLookup)newList.Fields["Lookup Column"];
lkp.LookupField = targetList.Fields["Title"].InternalName;

Is this OK or is there a better way around this?


I have created several lookups in the schema.xml without problems. The declaration uses the List attribute as you have in your example though I have never used the SourceID attribute. The only issue that has to be met is the order with which the lists are created. For example when I did this, I had to be sure that the list that was being looked into was created first. This has always worked for me. There is nothing wrong with using code either so it really depends on what you want to do.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.