Adding a Lookup Column to a SharePoint List
This took me a heckuva lot longer to get working right than I will ever admit. I thought the end result was nice and tidy. This example shows how to take a list from one web, and populate a column in another list based on the values from the first. Modifications to the first list will be reflected in any columns that reference that list via lookup.
SPSecurity.RunWithElevatedPrivileges(delegate()
{
using (SPSite website = new SPSite(SPContext.Current.Site.ID))
{
website.AllowUnsafeUpdates = true;
SPWeb newWeb = website.OpenWeb(_newWeb.ID);
newWeb.AllowUnsafeUpdates = true;
#region Add Lookup Column to new doc lib
SPDocumentLibrary newDocLib = (SPDocumentLibrary)newWeb.Lists["Documents"];
// Grab list guid and the web container
Guid customListGuid = ListManager.GetGuid(SPContext.Current.Web, “MyCustomWebList”);
newCRFDocLib.Fields.AddLookup(”Some Descriptive Field Name”, customListGuid, SPContext.Current.Web.ID, false);
// Add the new lookup field to the default view.
SPField fld = newCRFDocLib.Fields["Some Descriptive Field Name"];
SPView defaultView = newCRFDocLib.DefaultView;
SPViewFieldCollection viewFields = defaultView.ViewFields;
viewFields.Add(”Some Descriptive Field Name”);
defaultView.Update();
ListManager.ReorderField(newWeb.Lists["Documents"], fld, 0);
}
}
public static Guid GetGuid(SPWeb web, String listName)
{
foreach (SPList list in web.Lists)
{
if (true == list.Title.Equals(listName, StringComparison.OrdinalIgnoreCase))
return list.ID;
}
return Guid.Empty;
}