private void CreateLookup()
{
SPSite site = new SPSite("http://localhost/sites/employee");
SPWeb web = site.OpenWeb();
// Get the Department List from the web for lookups
SPList departmentList = web.Lists["Department"];
// Get the Employee List from the web
SPList employeeList = web.Lists["Employees"];
// Add a new lookup field to the Employee list called Departement
// that will use the Department list for it's values
employeeList.Fields.AddLookup("Department", departmentList.ID, false);
// Create 2 new departments in the Department list for lookups
AddDepartment(departmentList, "Information Services");
AddDepartment(departmentList, "Finance");
// Now create 5 employees with lookups into each Department
AddEmployee(employeeList, "Mickey Mouse", departmentList, "Information Services");
AddEmployee(employeeList, "Goofy", departmentList, "Finance");
AddEmployee(employeeList, "Donald Duck", departmentList, "Information Services");
AddEmployee(employeeList, "Daisy Duck", departmentList, "Information Services");
AddEmployee(employeeList, "Minnie Mouse", departmentList, "Information Services");
// Cleanup and dispose of the web and site
web.Dispose();
site.Dispose();
}
private void AddDepartment(SPList list, string name)
{
SPListItem newDepartmentItem = list.Items.Add();
newDepartmentItem["Title"] = name;
newDepartmentItem.Update();
}
private void AddEmployee(SPList list, string name, SPList deptList, string deptName)
{
SPListItem newEmployeeItem = list.Items.Add();
newEmployeeItem["Title"] = name;
newEmployeeItem["Department"] = FindDepartmentByName(deptList, deptName);
newEmployeeItem.Update();
}
private int FindDepartmentByName(SPList list, string name)
{
int itemId = 0;
SPQuery query = new SPQuery();
query.Query = "<Where><Eq><FieldRef Name='Title'/><Value Type='Text'>" + name + "</Value></Eq></Where>";
SPListItemCollection items = list.GetItems(query);
if(items.Count == 1)
itemId = items[0].ID;
return itemId;
}