HOW TO: Elegantly parse out either the ID or the VALUE of a SharePoint Lookup column in c#…

2012-12-17 MV: This is a short post but hopefully welcome post.
In SharePoint 2012 Lookup columns actually contain a string which is concatinates both the lookup column’s ID and its value.

That is, the “value” of a lookup columns looks like this:   “600;#1648 Long Bridge Road”
This lookup item’s “LookupID” = 600
This lookup items “LookupValue” = “1648 Long Bridge Road”
The value carried (inexplicably) around in the Lookup Colum’s “Value” property = “600;#1648 Long Bridge Road”


 When seeking to compare such a lookup to say a SingleLineText column value, you can imagine the frustration. Suddenly you’re running around trying to remember your RegEx syntax, thinking you need to somehow parse out a variable length left side to leave the much-desired right side of the value string.

No so, my intrepid little SharePointers. Please recall (as I just did) the amazingly powerful SPFieldLookupValue class!

Here’s a snippet:

//CREATE an SPFieldLookupValue object for the CourtUnitLookup property, so its VALUE can be readily stripped from its ID…
SPFieldLookupValue MACItemCourtUnit = new SPFieldLookupValue( MACItem[“IPT_CourtUnit_Lookup”].ToString() );

//PARSE out the VALUE portion of this LookupValue from the entire “ID;#VALUE” string…
String strMACItemCourtUnit = MACItemCourtUnit.LookupValue;

NO RegEx!
NO Pattern Matching!
NO arcane, client-hates-it-because-it’s-NOT-inheritable code.
Just a simply construct an SPFieldLookupValue using your hateful string as a parameter for the constructor, and take advantage of the built-in properties to extract either the LookupID or the LookupValue from the hateful string.




Leave a Reply

Your email address will not be published. Required fields are marked *