Often if you provision lists or libraries, your customer wants you to add a lookup column to another list, which may be in the same web. So you are starting with list definitions and do everything in the right way, but if you deploy your solution and create list instances from the source list and the list with the lookup, your lookup column is not connected to the source list. I don’t know why this happens, and i don’t care about the technical details why and why not. I’d rather share how to reconnect your defined lookup column to the source list.
Well, that’s what we want avoid:
What do we need? We need c# code, we put this into a feature event receiver or anything what will be used for it.
So our schema for the lookup field is the normal one:
In this code, we work with the SPWeb Object, the SPList of the list in which our lookup is defined. I found this nice <a href=”http://www.n8d.at/blog/lookup-fields-as-site-column-declarative-deployed/”>post where Stefan Bauer</a> explains really good what to do and i rented the code from him:
SPField lookupField = web.Lists[mylistID].Fields.TryGetFieldByStaticName(“LookupCol”);
if (lookupField != null)
XDocument fieldSchema = XDocument.Parse(lookupField.SchemaXml);
XElement root = fieldSchema.Root;
//Check lis definition
if (root.Attribute(“List”) != null)
string listUrl = root.Attribute(“List”).Value;
// Get the correct folder for the list
SPFolder listFolder = web.Lists[catListID].RootFolder;
if (listFolder != null && listFolder.Exists == true)
// Setting the list id of the schema
XAttribute attrList = root.Attribute(“List”);
if (attrList != null)
// Replace the url wit the id
attrList.Value = listFolder.ParentListId.ToString();
// Setting the souce id of the schema
XAttribute attrWeb = root.Attribute(“SourceID”);
if (attrWeb != null)
// Replace the sourceid with the correct webid
attrWeb.Value = web.ID.ToString();
// Update field with new schema
lookupField.SchemaXml = fieldSchema.ToString();
At first we get our SPField, that’s our lookup field. In this lookup field we catch the schema xml and we iterate trough it. We set some attributes: The ParentListId and the SourceId. The SourceID is the important one. With the source id we reconnect our lookupfield without changing anything like position, we do not need to delete the lookup and create it new.
That’s what we want to see:
Hope this helps.
..:: I LIKE SHAREPOINT ::..