Monday, June 8, 2015

Setting BCS data column value programmatically

When you try to set value to a BCS field programmatically, you must consider its differences from standard field. Rompen Patrick describes the technic in his blog.
The brief description is, that while setting value to BCS field, you must set value to a hidden field, too. This hidden field is created probably for showing BCS field data in Sharepoint UI.
private void SetBscFieldValue(string value)
{
    //Set true AllowUnsafeUpdates keeping its original value.
    bool allowUnsafeUpdatesValue = currentWeb.AllowUnsafeUpdates;
    currentWeb.AllowUnsafeUpdates = true;

    //Get a reference to the field.
    SPField field = item.Fields["BCSField"];

    //Get the field's entity name.  
    XmlDocument xmlData = new XmlDocument();
    xmlData.LoadXml(field.SchemaXml);
    string entityName = xmlData.FirstChild.Attributes["RelatedFieldWssStaticName"].Value;

    //Set the entity instance value.
    item[entityName] = EntityInstanceIdEncoder.EncodeEntityInstanceId(new object[] { value });

    //Set the field display value.
    item["BCSField"] = value;

    //Save the list item.
    item.Update();

    //Revert allow unsafe updates to its original value.
    currentWeb.AllowUnsafeUpdates = allowUnsafeUpdatesValue;
}

No comments:

Post a Comment