Simple data binding changes in VSTO 2.0 Beta 2

[Thanks to Mohit Gupta for his code examples that I quote in this entry]

We changed how simple data binding works in VSTO 2.0 Beta 2 from the Beta 1 behavior.

As you may know, simple data binding in VSTO 2.0--say binding an Excel named range to a "Name" column from a customers table--is basically one way. If the named range is changed, this will not automatically update the customers table the named range is bound to. There are a variety of reasons why we do this, the main one being that there is no event that fires consistently in Office telling you that the value of a cell changed. For example, a cell can change as a result of a formula update for example and no change event is fired by Excel.

So the burden is placed on the developer to have a button or some other UI gesture that commits the changes made in the named range back to the data source that the named range is bound to. We don't recommend you rely on Excel or Word change events to determine when to commit changes back as they are not always going to fire.

In VSTO 2.0 Beta 1, the way you'd write this code involved calling a method called "EndCurrentEdit". In Beta 2, we have a new recommended syntax shown below. In this code snippet, we have a named range called "NamedRange1", a button called "AcceptChanges" and a customersTable with a column called Name. We bind NamedRange1 to the Name column using the "Databindings.Add" line of code which creates a Binding object that is associated with NamedRange1's Value2 property. To commit any changes in NamedRange1 back to the database, the user clicks the AcceptChanges button in this example which grabs the Binding object associated with NamedRange1's Value2 property (this.NamedRange1.DataBindings["Value2"]) and calls the WriteValue() method on that Binding object. This moves the value of Value2 of NamedRange1 back to the customersTable.

private void Sheet1_Startup(object sender, System.EventArgs e)
{
this.NamedRange1.DataBindings.Add("Value2", customersTable, "Name");
this.AcceptChanges.Click += AcceptChanges_Click;
}

private void AcceptChanges_Click(object sender, EventArgs e)
{
this.NamedRange1.DataBindings[“Value2”].WriteValue();
}

The very observant will also notice another change from Beta1. In Beta2, we renamed the "Sheet1_Initialize" event to be "Sheet1_Startup" instead.