How do I read LookUp fields with multiple values in SharePoint?
Solution 1
For each of the SPField
s in the list's fields, you need to test the field's Type
.
If the type is SPFieldType.MultiChoice
, then you cast the SPField
to SPFieldChoice
and access the Choices
collection, which is a StringCollection
.
Solution 2
If you are specifically interested in LookUp fields with multiple values not just MultiChoice feilds, then following code should help:
item.Fields["LookFieldName"].Type == SPFieldType.Lookup;
SPFieldLookup LookUpField = item.Fields["LookFieldName"] as SPFieldLookup;
if (LookUpField.AllowMultipleValues)
{
SPFieldLookupValueCollection valueCollection = item[Field.Id] as SPFieldLookupValueCollection;
string[] arrLookupValues = (from SPFieldLookupValue val in valueCollection select val.LookupValue).ToArray<string>();
}
Matt Cashatt
I love to code and really enjoy being on Stackoverflow. It has taught me a ton.
Updated on June 09, 2022Comments
-
Matt Cashatt almost 2 years
Hi and thanks for looking!
Background
I have inherited an old .NET project based on SharePoint 2007 and have designed and external core library which merely accesses SP data, therefore making SP just a backend. Yes, I know it would be better to migrate to SQL, but the client doesn't agree.
The previous developers used a simple read method to read the data in a SP list:
SPList list = CurrentRootWeb.Lists["SomeListName"];
And then they access list properties through a dictionary of sorts (i.e. for each item in list, get item["SomeValue"]).
I am not skilled in SharePoint, so I don't know if this is the most efficient manner to go about accessing it's data.
Problem
How do I read LookUp fields with multiple values in SharePoint?
Every property they request seems to want a string in return. So
item[SomeString]
is okay, butitem[SomeList]
makes everything barf! I would have thought that a multi-value lookup list column comes in as a serialized or delimited string holding the selected values (example: "red;blue;green"). What am I missing?Thanks!
-
Matt Cashatt over 12 yearsThanks competent_tech! I am very incompetent when it comes to SharePoint--can you please tell me how to test the type in code? Only if you know without referencing anything. Thanks!
-
competent_tech over 12 yearsThat's going to depend on how you are accessing the fields. I assume that your code is doing something like foreach (SPField oField in list.Fields); if so, then you can just say: if (oField.Type == SPFieldType.MultiChoice)
-
samspot about 12 yearsAs a newbie sharepoint developer, this answer was very helpful and hard to find. Thanks also for giving a great example with SPLinq.