Reading and Writing to Lookup Field in Sharepoint

Lookup field is a field which links a child class to a parent class, it is an association kind, which allows a list item to reference another item from another list. However, reading and writing to a lookup field is different from a normal field. We need to use the class SPFieldLookupValue to archieve this.

First, it is important to understand that, whenever we create a Lookup field on a list, the value it stores for its reference item is not what we thought it was, ID. It is actually ID;#VALUE, where ID is the foreign key of the parent list item and VALUE is the title or whatever column we set of the parent list item.

So, to read a Lookup field in C#:

if (listItem["Material"] != null){
     SPFieldLookupValue spv = new SPFieldLookupValue(listItem["LOOKUP_NAME"].ToString());
     ddl.SelectedValue = spv.LookupValue.ToString();
}

What we have done here is simply get an instance of an SPFieldLookupValue by passing it the lookup field name and then aget its lookupvalue property. That will return the title of the parent list item.

To write to a Lookup field in C#:

SPList spList = web.Lists["ListName"];
int intSelectedId = Common.getItemId(ddl.SelectedValue, spList);
SPFieldLookupValue spv;
if (intSelectedId > 0)
{
    spv = new SPFieldLookupValue(intSelectedId, ddlM.SelectedValue);
    document["LOOKUP_NAME"] = spv;
}

Notice that we needed to get the parent item’s ID by passing it the title value. I created my own lookup method for this:

public static int getItemId(string strValue, SPList spList){
  SPQuery query = new SPQuery();
  query.Query = "<Where><Eq><FieldRef Name='Title' />
                  <Value Type='TEXT'>" + strValue + "</Value></Eq></Where>";
  if (spList.GetItems(query) != null){
       SPListItem result = spList.GetItems(query)[0];
       return result.ID;
   }
  else
       return 0;
}
Categories: Sharepoint 2007
Tags: