SharePoint 2007 - Add a Lookup Field to a List Template Element that references its own List
I had a real hard time coming up for a title for this post. Here is what I am trying to explain in the title. I had a need to create a custom List Template. This can be done via a Feature. The issue I ran across was I needed a Lookup Field in my list that contained values in another column in the same list. The problem was that when you create a Lookup List, behind the scenes, SharePoint is assigning the Guid of the list that you are performing the lookup in to the LookupList property. This works fine when doing this thru the user interface because the list exists when you add the column. But to place a lookup into a List Template, as far as I can tell anyways, is impossible to do via any of the schemas. It needs this Guid when it creates the field, which we obviously do not have when we are creating the List Template.
My solution was as follows: I created the list without that field and I added some code in the Feature receiver FeatureActivated method. This allowed me to programmatically add the lookup field AFTER the list was created.
public override void FeatureActivated(SPFeatureReceiverProperties properties)
using (SPWeb _SPWeb = properties.Web)
// the name of the list is set in the ListInstance Element of
// this Feature
SPList _SPList = (SPList)_SPWeb.Lists["ListName"];
if (_SPList != null)
// add a new lookup field to the list
_SPList.Fields.AddLookup("LookupField", _SPList.ID, false);
// update the list
// get a reference to the SPFieldLookup we just added
SPFieldLookup _SPFieldLookup = new SPFieldLookup(_SPList.Fields, "LookupField");
// get a reference to the default view
SPView _SPView = _SPList.DefaultView;
// add the field to the view if it is not there
// update the view
Now I have a lookup field in my list that points to a column in the same list! Happy coding!