SharePoint 2010: How do I populate a lookup field in C#?

I had the requirement to populate seeddata in a simple list structure that contained some lookup columns. The lookup requires the identifier/display text of the source object - in my case it was a ParentItem that was being used in the ChildItem table. I created a lookup column 'Parent' and added it the child list.

The following code resolved the problem.
Please note that this code is for seed data that has expected values and does no validation checking or use any defensive programming.

// Add items to the parent item
SPList parentList = web.Lists["ParentItem"];
SPListItem item = parentList.Items.Add();
item["Title"] = "Parent Header 1";
item.Update();

// Add the child item
SPList childList = web.Lists["ChildItem"];
item = childList.Items.Add();

SPListItem parentItem = GetHeaderItem(parentList, "Parent Header 1");

item["Title"] = "My Child Item";
item["Parent"] = new SPFieldLookupValue(parentItem.ID, parentItem.Title);
item.Update();

private SPListItem GetParentItem(SPList list, string title)
{
SPQuery query = new SPQuery()
{
Query = string.Format("<Where> <Eq> <FieldRef Name=\"Title\"></FieldRef> <Value Type=\"Text\">{0}</Value> </Eq> </Where>", title)
};

SPListItemCollection items = list.GetItems(query);
if (items.Count > 0)
{
return items[0];
}
else
{
return null;
}
}



Comments

Popular posts from this blog

SharePoint 2013: Error updating managed account credentials

Error deploying Nintex workflow: An item with the same key has already been added