Monday, November 13, 2006

.Net 2.0 Forms DataBinding - Manual refresh

I recently discovered how nice it was to use DataBinding. I liked using it so much that I spent 4+ hours making it work for my application. In my application my data was being changed in the background by a continuously running thread. I suppose because it was being modified outside the scope of the form, the bindings were not being updated. It took me awhile to figure out how to manually refresh these binding.

The solution was to subscribe to the CurrentItemChanged event and then to run ReadValue() on all the controls Bindings. Here is the code that resulted.
private delegate void CurrentItemChangedCallback(object sender, EventArgs e);
private void BindingSource_CurrentItemChanged(object sender, EventArgs e)
{
if(InvokeRequired)
{
CurrentItemChangedCallback d = new CurrentItemChangedCallback(BindingSource_CurrentItemChanged);
this.Invoke(d, new object[] { sender, e });
}
else {
foreach (Binding b in myControl.DataBindings)
{
b.ReadValue();
}
}
}
The code only updates the myControl control, but it could have just as easily iterated through all the controls in the form and refreshed all their bindings as well.

No comments: