1
votes

I have been able to programmatically add external (i.e. BDC) lookup fields to a list and I have also been able to add dependent external lookup fields to the same list. What I have not been able to figure out is how to programmatically add the dependent external lookup fields to the list's default view.

This article on MSDN gives an example of how to add a regular dependent lookup field to an SPView -but I have yet to find an example that shows how to programmatically add a dependent external lookup field to an SPView.

Below is the code in the FeatureActivated method of my EventReceiver that I am using to add the dependent external lookup fields to my SharePoint list and my attempt at adding the field to the list's default view.

var web = ((SPSite)properties.Feature.Parent).RootWeb;
var list = web.Lists.TryGetList("MyList");
var fldName = "EmployeeID";

var fld = list.Fields.CreateNewField("BusinessData", fldName) as SPBusinessDataField;

fld.SystemInstanceName = lobSystemInstanceName;
fld.EntityNamespace = entityNamespace;
fld.EntityName = entityName;
fld.BdcFieldName = entityFieldName;

//The dictionary object defined below contains key/value pairs that represent the 
//field name as a string along with a boolean flag that specifies whether or not 
//the secondary field should be added to the default view.
var secondaryFieldNames = new Dictionary<string, bool>()
                        {
                            {"FirstName", true},
                            {"LastName", true},
                            {"Title", false}
                        }
fld.SetSecondaryFieldsNames(secondaryFieldNames.Select(e => e.Key).ToArray());

var view = list.Views.DefaultView;

foreach (var secFld in secondaryFieldNames)
{
     var viewFieldName = String.Format("{0}: {1}", fldName, secFld.Key);

     if (!view.ViewFields.Exists(viewFieldName) && secFld.Value)
     {
          view.ViewFields.Add(viewFieldName);
          view.Update();
     }
}

As mentioned previously, the primary lookup field and all secondary lookup fields are successfully added to the list. The primary lookup field is successfully added to the list's default view. The seconday fields are not.

1

1 Answers

0
votes

Storing the viewfield collection in a variable did the trick for me (don't really know why).

foreach (var secFld in secondaryFieldNames)
            {
                var viewFieldName = String.Format("{0}: {1}", fldName, secFld.Key);
                var viewFields = view.ViewFields;
                if (!viewFields.Exists(viewFieldName) && secFld.Value)
                {
                    viewFields.Add(viewFieldName);
                    view.Update();
                }
            }