Monday, April 20, 2009

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:




Share your SharePoint Experiences with us...
As good as the SharePointKings is, we want to make it even better. One of our most valuable sources of input for our Blog Posts comes from ever enthusiastic Visitors/Readers. We welcome every Visitor/Reader to contribute their experiences with SharePoint. It may be in the form of a code stub, snippet, any tips and trick or any crazy thing you have tried with SharePoint.
Send your Articles to sharepointkings@gmail.com with your Profile Summary. We will Post them. The idea is to act as a bridge between you Readers!!!

If anyone would like to have their advertisement posted on this blog, please send us the requirement details to sharepointkings@gmail.com