2010, Development Blog, SharePoint
Create cross-site lookup fields in SharePoint 2010 utilizing site columns
This is documented on a few other blogs, including MSDN, but none of them were super clear. Everyone processes information differently, so I hope this helps you out. Please note that I’m using this code in my FeatureActivated even receiver.
This is handy when:
- You look up information in the same site collection
- You need to have one site column point at another site column in the same Site Collection, but across different web sites.
In my code, I refer to:
- SourceList (the list utilizing the site column where you are getting the information from)
Assume:
- New Column Name is the new site column I am creating in the current website
- Lookup Column Name is the existing site column, used in Source List, which lives in a different website /Subsite_Path_With_Source_List
In a nutshell, I am here:
/
and I want to look up information from this list:
/Subsite_Path_With_Source_List/Lists/Source List
Here is the code (update the items in bold and you should be all set):
using (SPWeb web = SPContext.Current.Web.Site.RootWeb) { try { // Open the web containing the source list SPWeb webWithSourceList = SPContext.Current.Site.OpenWeb("Subsite_Path_With_Source_List"); // Get the source list SPList lookupList = webWithSourceList.Lists["Source List"]; // If it exists if (lookupList != null) { string lookupFieldName = "New Column Name"; string sourceFieldName = "Lookup Column Name"; web.Fields.AddLookup(lookupFieldName, lookupList.ID, webWithSourceList.ID, false); SPFieldLookup lookupField = (SPFieldLookup)web.Fields[lookupFieldName]; lookupField.LookupField = lookupList.Fields[sourceFieldName].InternalName; lookupField.Update(true); myContentType.FieldLinks.Add(new SPFieldLink(lookupField)); myContentType.Update(); } // Dispose of the web webWithSourceList.Dispose(); } catch (Exception) { throw; } }
About Author
Comments are closed