Skip to main content

Display SharePoint Lookup column in custom application

The task

We have a SharePoint list with a column of type Lookup. We also have an ASP .NET application where we need to display this SharePoint column as a drop down list.

Solution

1. In your ASP .NET application inside the event where you create your controls - i.e. CreateChildControls event - write the following code:


DropDownList drp = new DropDownList();
SPFieldLookup lkp = (SPFieldLookup)spField;
Guid gG = new Guid(lkp.LookupList);

SPWeb web = ... // initialize your SPWeb object

try
{
SPList list = web.Lists[gG];
foreach (SPListItem item in list.Items)
{
ListItem litem = new ListItem(item[lkp.LookupField].ToString(), item["ID"].ToString());
drp.Items.Add(litem);
}
}
catch
{
// put some error handling here...
}
this.Controls.Add(drp);

// spField - is an object of type SPField you can initialize it like the following:
// SPField spField = your_SharPoint_list.Fields[index or display name of your lookup column];

2. If you want to save selected values from you drop down list back to SharePoint Lookup column do the following:

SPListItem item = list.Items.Add(); // in this case we are creating new record
item[lookupfield.Id] = new SPFieldLookupValue(int.Parse(drp.SelectedItem.Value), drp.SelectedItem.Text);
item.Update();

Enjoy.


Comments