Friday, 1 July 2011

How to Read,Update LookUp fields in SharePoint List

Lookup fields in SharePoint provides a great way to pickup dynamically changing values from a dropdown list.But programmatic access of this type of fields is not straightforward. The actual list item value is stored as ID:#Value. Where ID is reference to the id of referring list and value is the value selected. SharePoint SDK provides APIs to read and update lookup fiedls. SPFieldLookupValue object can be used to read and update/insert lookup fields.
For example:
Lets create a sample master list "Skills ", add following values:
ASP.Net
C#
SQL

Following is screen shot of the master list "Skills":






Now create another custom list "My Skills", with a lookup field which refers to Title column of "Skills" list, which is created earlier.

Following code snippet, reads and updates the "TechSkills" field of "My Skills" list.


using (SPSite site = new SPSite("http://servername"))
{
using(SPWeb web = site.OpenWeb())
{
SPList list = web.Lists["My Skills"]; //List which has lookupfield TechSkills
SPListItemCollection itemCollection;
itemCollection = list.Items;
foreach (SPListItem item in itemCollection)
{
SPFieldLookupValue lookupField = new SPFieldLookupValue(item["TechSkills"].ToString());
string lookUpValue = lookupField.LookupValue;
Console.WriteLine("List item actual value:" + item["TechSkills"].ToString());
Console.WriteLine("List item lookfield value:" + lookUpValue);
}
SPListItem listItem = itemCollection[0];
listItem["Skill Name"] = new SPFieldLookupValue(1, "ASP.Net"); //ID field of ASP.Net is 1
listItem.Update();
}
}