I've recently had to work on a project using DataBinding. All seemed to go well until I ran into some strange issues.
This is the first of a few posts describing these issues and how to work around them.
I've got some bound ComboBox columns in a bound DataGridView and all works well, but the problem is when the form closes, and starts Disposing controls, I get this message:
"Message: ArgumentException: Cannot bind to the property or column State on the DataSource.
Parameter name: dataMember"
It seems to affect the ComboBoxes bound to the NameValueLists where the Text property is databound.
The solution is to clear all DataBinding before Dispose().
Step 1: Create a method to clear DataBinding recursively...
using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using System.ComponentModel;
using System.Reflection;
namespace DataBinding {
internal sealed class Utilities {
/// <summary>
/// Clears all databindings from the control and all child controls.
/// </summary>
/// <param name="ctl">The control from which to clear the databindings.</param>
public static void ClearBindings(Control ctl) {
Binding[] bindings = new Binding[ctl.DataBindings.Count];
ctl.DataBindings.CopyTo(bindings, 0);
ctl.DataBindings.Clear();
foreach (Binding bnd in bindings)
if (null != bnd) TypeDescriptor.Refresh(bnd.DataSource);
PropertyInfo dataSourceProperty = ctl.GetType().GetProperty("DataSource");
object[] obj = new object[]{};
if (null != dataSourceProperty)
dataSourceProperty.SetValue(ctl, null, obj);
foreach (Control child in ctl.Controls)
ClearBindings(child);
}
}
}
Step 2: Call the ClearBindings method when the Form has been closed...
private void Form1_FormClosed(object sender, FormClosedEventArgs e) {
// Release bindings
Utilities.ClearBindings(this);
}
That should do the trick.