Get and Set a SharePoint Lookup Field Value Using Server Object Model C#

At this hint, I will explain

How to Get and Set a SharePoint Lookup Field (Single Value) using Server Object Model C#

Set a SharePoint Lookup Field value


using (SPSite site = SPContext.Current.Site)
{
using (SPWeb web = site.OpenWeb())
{
// Allow Unsafe Updates to prevent the cross site scripting
web.AllowUnsafeUpdates = true;
// Get The SPList
SPList list = web.Lists["List Name"];
// Add a new list item
SPListItem item = list.Items.Add();
// Set the default Title field
item["Title"] = "String Value";
//Set the Lookup Field - Single Value
item["The Lookup Field Name"] = new SPFieldLookupValue("A 32-bit integer that specifies the ID of the lookup field", "A string that contains the value of the lookup field");
// Submit your Item
item.Update();
web.AllowUnsafeUpdates = false;
}
}

Get a SharePoint Lookup Field value

 using (SPSite site = SPContext.Current.Site)
{
using (SPWeb web = site.OpenWeb())
{
// Get The SPList
SPList list = web.Lists["List Name"];
// Get a list item By ItemID
SPListItem item = list.GetItemById("A 32-bit integer that specifies the ID of List Item");
//Get Lookup Field - Single Value
SPFieldLookupValue SingleValue = new SPFieldLookupValue(item["The Lookup Field Name"].ToString());
int SPLookupID = SingleValue.LookupId;
string SPLookupValue = SingleValue.LookupValue;
}
}
Download 

You can download the full solution from TechNet gallery at SharePoint Lookup Field Operations via SSOM C#

See also
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s