During creating a new Lookup column, If the AllowMultipleValues is checked, the column is multiple values; else, it's a single value.
In case, the lookup column is a single value, the field value is an object of type SPFieldLookupValue with
You might also like to read Using Lookup Field in Calculated Column SharePoint
In this article, we will explain How to use Server Side Object Model (C#) to do the following:
The below code shows How to set a SPLookup field (Single Value) in a SharePoint List new item.
using
(SPSite site = SPContext.Current.Site)
{
(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
"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();
false
}
The below code shows How to set a SPLookup field (Multiple Values) in a SharePoint List new item.
"string value"
//Set Lookup Field - Multiple Values
SPFieldLookupValueCollection itemValues =
SPFieldLookupValueCollection();
foreach
(ListItem litem
in
your collection)
itemValues.Add(
));
] = itemValues;
The below code show How to get a SPLookup field (Single Values) based on an existing item in a SharePoint List.
// 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 =
SPFieldLookupValue(item[
].ToString());
int
SPLookupID = SingleValue.LookupId;
string
SPLookupValue = SingleValue.LookupValue;
The below code shows How to get a SPLookup field (Multiple Values) in a dropdown list based on an existing item in a SharePoint List.
"LookupField"
//Get Lookup Field - Multiple Values
SPFieldLookupValueCollection MultipleValues = item[
]
as
SPFieldLookupValueCollection;
(SPFieldLookupValue itemValue
MultipleValues)
ListItem litem =
ListItem();
litem.Text = itemValue.LookupValue;
litem.Value = itemValue.LookupId.ToString();
dropdownlist.Items.Add(litem);