Wednesday, September 30, 2009

Reading lookup field value from SharePoint List item

While reading a lookup column value, it is observed that value returns contains a number and character # followed by the actual lookup value selected. Spitting or substring the value may not be the right way to extract the actual lookup value.

SharePoint provides a object SPFieldLookupValue to read Id and the Value of referenced list item.

using (SPSite site = new SPSite(“http://localhost”))

{

using(SPWeb web = site.OpenWeb())

{

SPList list = web.Lists[“MyList”];

SPListItem item = list.Items[0];

String strvalue = item[“lookupColumn”];

//this value comprises of number (id) and the lookup value with #.

SPFieldLookupValue lookup = new SPFieldLookupValue(strvalue);

String myLookupValue = lookup.LookupValue;

//lookup.LookupId returns the id for the referenced list item

//reading multi-valued lookup field value
SPFieldLookupValueCollection lookupCollection = new SPFieldLookupValueCollection(strvalue);

List<string> strLookupValues =new List<string>();

foreach( SPFieldLookup lookupItem in lookupCollection)

{

strLookupValues.Add(lookupItem.LookupValue);

Console.Write(lookupItem.LookupValue);

}

}

}

No comments: