My Problem

Today I had a requirement to make a lookup field required and set the default value. For a lookup field this isn’t possible within the SharePoint 2010 interface.

My solution

Programmatically the SPFieldLookup also doesn’t have the options available. However casting the Lookup to an SPField does the trick.

public overridevoid FeatureActivated(SPFeatureReceiverProperties properties)
{
try
{
SPWeb web = (SPWeb)properties.Feature.Parent;
SPList list = web.Lists[“MyList”];
SPField lookup = (SPField)list.Fields[“My Lookup”];

lookup.DefaultValue = “1;#Value 1”;
lookup.Required = true;
lookup.Update();
}
catch(Exception Ex)
{
// do what ever you want
}
}

Advertisements