Compartilhar via


Reading & Updating Lookup Fields

My client had two lists. First list (appropriately named “Lookup List”) contains a list of application names, stored in the “Application Name” column. The other list (Example List) contains a lookup column (Application Name, again) that points back to “Lookup List.Application Name” and a hyperlink column (xyz) which has the “application name” as the title. They’ve populated the second list with a lot of items. For each item, only the hyperlink column contains data, the lookup column is not populated with any data. The code below was written to programmatically populate the lookup column based on the data in the hyperlink column.

 

I’m posting this code to show how you can read and update lookup columns.

SPWeb web = SPContext.Current.Site.OpenWeb(siteUrl);

 

string listUrl = web.ServerRelativeUrl + "/Lists/Example%20List/AllItems.aspx";

SPList list = web.GetListFromUrl(listUrl);

 

 

web.AllowUnsafeUpdates = true;

foreach (SPListItem item in list.Items)

{

    SPFieldLookup appNameFieldValue = item["Application Name"] as SPFieldLookup;

    if (appNameFieldValue == null || string.IsNullOrEmpty(appNameFieldValue.ToString()))

    {

        string urlFieldValue = item["xyz"] as string;

        int firstComma = urlFieldValue.IndexOf(',');

        string tempAppName = urlFieldValue.Substring(firstComma + 2);

 

        string lookupListUrl = web.ServerRelativeUrl + "/Lists/Lookup%20List/AllItems.aspx";

        SPList lookupList = web.GetListFromUrl(lookupListUrl);

        foreach (SPListItem lookupItem in lookupList.Items)

        {

            if (lookupItem["Application Name"].ToString() == tempAppName)

            {

                item["Application Name"] = new SPFieldLookupValue(lookupItem.ID, tempAppName);

                item.Update();

            }

        }

    }

}