A lookup column which refers to items from a whole different site collection does not work. But to create a lookup column programmatically and add an additional fields related to this lookup column will work. How? Let me show you with a simple example.
We have a list with IT Projects and a list with IT Applications which is in the parent site of the IT Projects list and some additional information in SharePoint.
We would like to choose an IT Application in the IT Projects list and see some additional information about the Application. That is our scenario and that the result:
1) Accessing the list by c#
SPList pojectList;
SPList itApplication;
SPSite site = new SPSite(“yoursite”);
SPWeb web = site.openWeb();
pojectList= web.Lists[“pojectList”];
itApplication= web.ParentWeb.Lists[“itApplication”];
2) Adding the first lookup column to the ITProject list
string lookUp = pojectList.Fields.AddLookup(“IT App”, itApplication.ID, false);
SPFieldLookup fieldLookup = (SPFieldLookup)pojectList.Fields.GetFieldByInternalName(lookUp);
Now we have to tell the LookupWebID cause it is a list from Parentweb.
fieldLookup.LookupWebId = web.ParentWeb.ID;
And then we tell the lookup which field it should lookup.
fieldLookup.LookupField = itApplication.Fields[“IT App”)].InternalName;
fieldLookup.Update();
Now you should see already the field in your list. It should look like this:
3) Create the additional fields dependent on the lookup
Same procedure as before but this time we create an “AddDependentLookup” and use the ID of the first lookup column we create earlier this morning.
string depLookUp = pojectList.Fields.AddDependentLookup(“IT App: Responsible”, fieldLookup.Id);
SPFieldLookup fieldDepLookup = (SPFieldLookup)pojectList.Fields.GetFieldByInternalName(depLookUp);
Again, we have to set the parent WebID again.
fieldDepLookup.LookupWebId = web.ParentWeb.ID;
fieldDepLookup.LookupField = itApplication.Fields[“ITResponsible”].InternalName;
fieldDepLookup.Update();
And your result should look like this:
Now repeat step 3 till you have all your necessary fields in your primary list, in our case the ITProject list.
After these steps, i can recommend to think about adding these fields or one of them to your custom or default view of the list:
SPView view = pojectList.DefaultView;
view.ViewFields.Add(“ITApplication”);
view.Update();
You’re done.
..:: I LIKE SHAREPOINT ::..
Many thanks! 🙂
But how can I set internal name for the additional lookup fields?
Thanks for the article. Works like a charm.
I need to do this using PowerShell instead.