Tuesday, July 17, 2012

SPFieldLookupValue and SPFieldLookupValueCollection

If you want to retriever lookup field from list then good practice is to use SPFieldLookupValue rather than string manipulation.

Here is the example how to use retrieve lookup value from SharePoint list.

SPSite site = new SPSite("http://spvm");
SPWeb web = site.OpenWeb();
SPList list = web.Lists["DemoList"];
SPListItem item = list.GetItemById(1);
SPFieldLookupValue objLookupFieldValue = new SPFieldLookupValue(item["lookup"].ToString());


Once you get this SPFieldLookupValue (objLookupFieldValue) object you will get following properties.

objLookupFieldValue.LookupValue = value of the parent list item.
objLookupFieldValue.LookupId = item id of the parent list item (reference id)


These are small things that will help you to make your software robust.
If Lookup is multi select then you have to use SPFieldLookupValueCollection.

SPFieldLookupValueCollection objLookupFieldValueCol = new SPFieldLookupValueCollection(item["lookup"].ToString());
for (int i = 0; i < objLookupFieldValueCol.Count; i++)
{
SPFieldLookupValue singlevalue = objLookupFieldValueCol[i];
//use singlevalue with same way as single select
}

No comments:

Post a Comment