SP2010: Setting BCS column and related fields

I’ve been struggling for a while to programmatically set BCS columns. Setting the column itself isn’t that hard, but it’s getting all the related fields to show data too that’s a challenge. There seems to be no out of the box method to do this, so I’ve created one myself. Without further ado, let’s get to the code!

[sourcecode language=”csharp”]
/// <summary>
/// Set all secondary BCS fields for a given entity
/// </summary>
/// <param name=”listItem”>The item to set the fields for</param>
/// <param name=”dataField”>The BCS field itself</param>
/// <param name=”entityInstance”>The entity to get the values from</param>
private static void SetSecondaryFields(SPListItem listItem, SPBusinessDataField dataField, IEntityInstance entityInstance)
// Convert the entity to a formatted datatable
DataTable dtBDCData = entityInstance.EntityAsFormattedDataTable;

// Set the BCS field itself (Display Value)
listItem[dataField.Id] = dtBDCData.Rows[0][dataField.BdcFieldName].ToString();

// Get the specific finder method to get the columns that returns
IMethodInstance method = entityInstance.Entity.GetMethodInstances(MethodInstanceType.SpecificFinder)[0].Value;
ITypeDescriptorCollection oDescriptors = method.GetReturnTypeDescriptor().GetChildTypeDescriptors()[0].GetChildTypeDescriptors();

// Set the column names to the correct values
foreach (ITypeDescriptor oType in oDescriptors)
if (oType.ContainsLocalizedDisplayName())
if (dtBDCData.Columns.Contains(oType.Name))
dtBDCData.Columns[oType.Name].ColumnName = oType.GetLocalizedDisplayName();

// get the secondary field display names; these should be set
string[] sSecondaryFieldsDisplayNames = dataField.GetSecondaryFieldsNames();

// loop through the fields and set each column to its value
foreach (string columnNameint in sSecondaryFieldsDisplayNames)
Guid gFieldID = listItem.Fields[String.Format(“{0}: {1}”, dataField.Title, columnNameint)].Id;
listItem[gFieldID] = dtBDCData.Rows[0][columnNameint].ToString();

To use this to update a list item, call it like this:

[sourcecode language=”csharp”]
SPBusinessDataField dataField = listItem.Fields[“BCSField”] as SPBusinessDataField;
listItem[dataField.RelatedField] = customerId;
SetSecondaryFields(listItem, dataField, entityinst);

Special thanks to Wade A Hunter for providing the guidelines on how to do this in 2007, this code is based on that. See: http://wadehuntersblog.blogspot.com/2010/10/working-with-sharepoint-2007-business.html


Related posts

Latest posts

Leave a Comment

Leave a Reply

Your email address will not be published. Required fields are marked *