SharePoint2010: Inserting/Updating a Lookup Field in a SP List
Problem
For values in a particular column in a SharePoint list, suppose list "A" , we can also refer to column in another list, suppose list B, simply by defining a column in list A as a lookup column of list B.As I assume you know how to do that. the further is step is to update or insert values into this lookup column programatically using SP's server object model.
Prerequisite
The value in a look up field is made of the ID of the lookup filed concatenation with ;# and Name of the lookup field (that actually shows up in the). For example if we are refering to a list named Annoucement, in another list Projects then we to add a task programmatically, we concatinate, ID of the item in the Annoucement list + ;# + Title of the Annoucement (The column selected while creating the lookup column as shown in the figure). So we can have: 1;#Project Analysis being carried outSolution
To do that we simply need to know the ID of the item in the list and the other field that you want to display
using (SPSite site = SPContext.Current.Site) { SPFieldLookupValue value = new SPFieldLookupValue(); site.AllowUnsafeUpdates = true; using (SPWeb web = site.OpenWeb()) { web.AllowUnsafeUpdates = true; SPList list = web.Lists["Enter Your ListName"]; item = list.Items.Add(); string fieldValue = "Enter the ID" + ";#" + "Enter the Name"; value = new SPFieldLookupValue(fieldValue); item["Column Name"] = value; item.Update(); } }The above code is sort of pseudo but I believe it is quite understandable.
Hope this helps
Cheers
Comments
Post a Comment