Sunday, 25 May 2014

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";

// 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);

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];
return null;

No comments:

Post a comment