Lookup values are internally referenced as a combination of ID(int) and field value(string) in the following format: 1;#FirstItem.
The class offered by SharePoint for lookup values is SPFieldLookupValue. The method SPFieldLookupValue takes 1 or 2 values:
- “1;#FirstItem” (string)
- lookupId and lookupValue. Obviously the lookupId represents the field’s ID, lookupValue represents the field’s value.
Obviously you have to know the ID and value of the new item to set to the lookup field.
To enumerate all the possible items of the lookup list:
string itemsListed = string.Empty;
SPListItemCollection sources = web.Lists[“Source”].Items;
foreach (SPListItem item in sources)
{
itemsListed += item[“ID”].ToString() + “;#” + item[“Title”].ToString() + System.Environment.NewLine;
}
An example of the content of itemsListed:
1;#FirstItem
2;#SecondItem
3;#ThirdItem
To search for a specific item you can use a CAML query:
SPQuery query = new SPQuery();
string toSearchFor = “ThirdItem”;
query.Query = “<Where><Eq><FieldRef Name=’Title’ /><Value Type=’Text’>” + toSearchFor + “</Value></Eq></Where>”;
SPListItemCollection collection = web.Lists[“Source”].GetItems(query);
If(collection.Count == 1)
{
int idOfItem = int.Parse(collection[0][“ID”].ToString());
string totalLookup = idOfItem.ToString() + “;#” + toSearchFor;
}
I just wanted to comment your blog and say that I really enjoyed reading your blog post here. It was very informative and I also digg the way you write! Keep it up and I’ll be back to read more soon mate