|Important||This document may not represent best practices for current development, links to downloads and other resources may no longer be valid. Current recommended version can be found here. ArchiveDisclaimer|
Represents a lookup field.
Assembly: Microsoft.SharePoint (in Microsoft.SharePoint.dll)
If you set properties of the SPFieldLookup class you must call the Update method for changes to take effect in the database.
An SPFieldLookup object can be rendered through the LookupField server control.
The SPFieldLookup class corresponds to the Lookup data type that is specified through the Type attribute of the Field element.
Lookup Field Values
By default, lookup fields do not allow multiple field values. In this case, the field value is an object of type String. The string is in the following format:
In this format, Id is the identifier for the list item that the lookup field points to and Value is the value of the field that the lookup field points to. The two parts of the string are delimited by the characters ";#". If Value contains a semicolon (";"), it is escaped with a semicolon (";;").
For example, if the lookup field points to the third list item and the value of the field that the lookup field points to is "I gnaw on old tires; it strengthens my jaw", then the following string is returned:
3;#I gnaw on old tires;;it strengthens my jaw
You can parse this string yourself, or you can pass it as an argument to the constructor for an SPFieldLookupValue object. Then you can get the list item identifier from the LookupId property, and the value of the field in the list item from the LookupValue property.
You can allow a lookup field to have multiple values by setting the AllowMultipleValues property. When the AllowMultipleValues property returns true, the field value is an object of type SPFieldLookupValueCollection.
If you call the SPFieldLookupValueCollection.ToString() method, you will get a string that contains a series of substrings, each with a single value in the format Id;#Value. The substrings themselves use the same delimiter, ";#". For example, the following string represents the value of a multiple value lookup with two values:
3;#a field value;#7;#another field value
Rather than parsing this string, it is more efficient to simply enumerate the SPFieldLookupValue objects in the SPFieldLookupValueCollection, taking each value from the LookupValue property.