Sharepoint Lookup Field

First of all we need to know a little on SharePoint lookup fields before proceeding further. Lookup fields are the reference fields created in any SharePoint list or library which provides a mapping between columns from another list i.e. it is just like a foreign key which helps build relationship between lists.

While developing custom solutions there is often a need to retrieve data from a list or update data in a list but it’s a bit different when the task is performed for a lookup field. Generally lookup data are stored as ID – Name pair separated with some special characters (i.e. ID;#Name).

In this tip I will try to provide some code samples in VB.Net which will help retrieve / update lookup data of specific list. To illustrate the things I will be using a “Contacts” list which will be having “CompanyName” as a lookup field from “Companies” list.
Retrieve lookup data and segregate them as value and text fields

'get list instance
Dim cntLst As SPList = web.Lists("ContactsList")
 
'get the list item by ID
Dim cntItem As SPListItem = cntLst.GetItemById(contactID)
 
'retrieve lookup data and display the ID / Name values in a label control
If Not cntItem("ColumnCompanyName") Is Nothing Then
       Dim delim() As String = {";#"}
       Dim lkpCompany() As String = cntItem("ColumnCompanyName").ToString().Split(delim, StringSplitOptions.None)
       Me.lblDisplay.Text = String.Format("Company ID: {0} and Company Name: {1}", lkpCompany(0), lkpCompany(1))
End If

Update lookup data

'set the value and text field for the lookup column belonging to the specific list item
cntItem("ColumnCompanyName") = New SPFieldLookupValue(CInt(Me.cmbCompany.SelectedValue), Me.cmbCompany.SelectedItem.Text)
 
'update the list item
cntItem.Update()
150 150 Burnignorance | Where Minds Meet And Sparks Fly!