Search code examples
sharepoint-2010

Get the lookup field value for a list item in SharePoint 2010 using C#


I am relatively new to sharepoint and I'm trying to write a web service to return our sharepoint inventory data as xml. It works good except that one of those list includes a lookup field and the generated xml contains "Microsoft.SharePoint.Client.FieldLookupValue" instead of the expected string value of the lookup field.

This is the code I'm using to generate the xml:

resultList = remoteWeb.Lists.GetByTitle("Cam Devices");
context.Load(resultList);
context.ExecuteQuery();
//Now its time to reach list's items
items = resultList.GetItems(new CamlQuery());
context.Load(items);
context.ExecuteQuery();
foreach (ListItem item in items)
{
    rootNode.AppendChild(doc.CreateElement("ID")).InnerText = "pcat:401824";
    rootNode.AppendChild(doc.CreateElement("Category")).InnerText = "Cam Devices";
    rootNode.AppendChild(doc.CreateElement("Kimlik")).InnerText = Convert.ToString(item["ID"]);
    rootNode.AppendChild(doc.CreateElement("Isim")).InnerText = Convert.ToString(item["Location0"]) + " >> " + Convert.ToString(item["Brand"]) + " >> " + Convert.ToString(item["ID"]);
}

item["Location"] is the lookup field and it has a value with the type FieldLookupValue, how can I get the lookup value as a string?


Solution

  • Ok, successfully get the lookup field's value by using following code syntax:

    string Location = "";
    if (item["Location0"] != null)
    {
        var fl = (SPFieldLookupValue)item["Location0"];
        Location = fl.LookupValue;
    }