Creating lookup fields using CAML and Code

If you have attempted to create lookup columns by defining fields in Schema.xml than you are probably aware of the fact that List attribute in Field element needs the GUID of the list and as GUID is generated by MOSS when the list is created it is not going to work in any real world deployment scenarios. The pain and work around of programmatically creating the Lookup field is well documented at The pain of creating lookup fields “

I added Lookup fields top my list programmatically with ease, but the problem was on the NewForm.aspx and EditForm.aspx the fields appeared at bottom of the form, I could not find any easy way to change the order of rendered fields other than customizing the forms itself which looked a bit of a work. That led me to look for an alternative to programmatically adding the Lookup Field as if you add any field using <Fields… collection in Schema.xml than Fields are rendered in the same order as their order in the <Fields…. Collection.

Chris O’Brien has an interesting approach to the solution using both CAML and code.

Finally here is what I settled for:

Add LookUp field in Scheme.xml’s <Fields… collection, and make sure List attribute on the Field element is not set, because we will assign the value of list element programmatically from the feature receiver.

<Field Name=InternalCourse DisplayName=Internal Course Type=Lookup Required=TRUE ShowField=CourseDetail ID={12240ECF-1E9A-4687-A52D-BC3C97626AD9}> </Field>

Now update the LookUp field in your feature receiver

SPList trainingRequest = web.Lists[destinationList];
SPFieldLookup
lookUp = trainingRequest.Fields[“Internal Course”] as SPFieldLookup;
lookUp.LookupList = web.Lists[“sourceList”].ID.ToString(“B”).ToLower();
lookUp.Update();

Reflect the LookupList property and it makes it clear that if List attribute is specified in CAML than programmatically setting the LookupList property will throw an exception.

MOSS LookUp Field

Advertisements

2 thoughts on “Creating lookup fields using CAML and Code

  1. can you please share this code with me.
    I am trying to create a custom list which should hold the lookup field and this is a sitelevel column so i got stumbled over here.

    Can you please help me out

    Regards,
    Raghu

    • Hi the snippet above is all the code needed in your Feature receiver to setup lookup column, if you are using SharePoint 2010, this is no longer need as you can specify the list using List=”Lists/List Name” syntax in Field schema itself

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s