In this article, we will explain how to programmatically -
- Set a SharePoint Lookup Field (Multiple Values) via SSOM C#.
- Get a SharePoint Lookup Field (Multiple Values) via SSOM C#.
- Set a SharePoint Lookup Field (Single Value) via SSOM C#.
- Get a SharePoint Lookup Field (Single Value) via SSOM C#.
SET SPLOOKUP FIELD (MULTIPLE VALUES) USING SSOM C#
- using(SPSite site = SPContext.Current.Site) {
- using(SPWeb web = site.OpenWeb()) {
-
- web.AllowUnsafeUpdates = true;
-
- SPList list = web.Lists["List Name"];
-
- SPListItem item = list.Items.Add();
-
- item["Title"] = "string value";
-
- SPFieldLookupValueCollection itemValues = new SPFieldLookupValueCollection();
- foreach(ListItem litem in your collection) {
- itemValues.Add(new SPFieldLookupValue("A 32-bit integer that specifies the ID of the lookup field", "A string that contains the value of the lookup field"));
- }
- item["The Lookup Field Name"] = itemValues;
-
- item.Update();
- web.AllowUnsafeUpdates = false;
- }
- }
GET SPLOOKUP FIELD (MULTIPLE VALUES) USING SSOM C#
- using(SPSite site = SPContext.Current.Site) {
- using(SPWeb web = site.OpenWeb()) {
-
- SPList list = web.Lists["LookupField"];
-
- SPListItem item = list.GetItemById("A 32-bit integer that specifies the ID of List Item");
-
- SPFieldLookupValueCollection MultipleValues = item["The Lookup Field Name"] as SPFieldLookupValueCollection;
- foreach(SPFieldLookupValue itemValue in MultipleValues) {
- ListItem litem = new ListItem();
- litem.Text = itemValue.LookupValue;
- litem.Value = itemValue.LookupId.ToString();
- dropdownlist.Items.Add(litem);
- }
- }
- }
SET SPLOOKUP FIELD (SINGLE-VALUE) Via SSOM C#
- using(SPSite site = SPContext.Current.Site) {
- using(SPWeb web = site.OpenWeb()) {
-
- web.AllowUnsafeUpdates = true;
-
- SPList list = web.Lists["List Name"];
-
- SPListItem item = list.Items.Add();
-
- item["Title"] = "String 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");
-
- item.Update();
- web.AllowUnsafeUpdates = false;
- }
- }
GET SPLOOKUP FIELD (SINGLE-VALUE) USING SSOM C#
- using(SPSite site = SPContext.Current.Site) {
- using(SPWeb web = site.OpenWeb()) {
-
- SPList list = web.Lists["List Name"];
-
- SPListItem item = list.GetItemById("A 32-bit integer that specifies the ID of List Item");
-
- 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 at SharePoint Lookup Field Operations via SSOM C#.
CONCLUSION
In this article, I have explained how to get and set SharePoint lookup field (single/multiple) values programmatically via Server Side Object Model in C#.