I have a CheckBox
that has it's Checked
property bound to a bool value. During the CheckedChanged
event, some logic runs which uses the bool property on the data source.
My problem is the first time the CheckBox
gets checked by the user, the bound data source does not get updated. Subsequent updates work fine though.
Here's some sample code for testing the problem. Just create a blank form and add a CheckBox
to it.
public partial class Form1 : Form
{
private bool _testBool;
public bool TestBool
{
get { return _testBool; }
set { _testBool = value; }
}
public Form1()
{
InitializeComponent();
checkBox1.DataBindings.Add(new Binding("Checked", this, "TestBool"));
checkBox1.CheckedChanged += new EventHandler(checkBox1_CheckedChanged);
}
void checkBox1_CheckedChanged(object sender, EventArgs e)
{
checkBox1.BindingContext[this].EndCurrentEdit();
Debug.WriteLine(TestBool.ToString());
}
}
The first time I check the box, the TestBool
property remains at false, even though checkBox1.Checked
is set to true
. Subsequent changes do correctly update the TestBool
property to match checkBox1.Checked
though.
If I add a breakpoint to the CheckedChanged
event and check out checkBox1.BindingContext[this].Bindings[0]
from the immediate window, I can see that modified = false
the first time it runs, which is probably why EndCurrentEdit()
is not correctly updating the data source.
The same thing also occurs with using a TextBox
and the TextChanged
event, so this isn't limited to just CheckBox.Checked
.
Why is this? And is there a generic common way of fixing the problem?
Edit: I know of a few workarounds so far, although none are ideal since they are not generic and need to be remembered everytime we want to use a Changed
event.
- setting the property on the datasource directly from the CheckedChanged event
- finding the binding and calling
WriteValue()
- hooking up the bindings after the control has been loaded
I am more concerned with learning why this is happening, although if someone knows of a standard generic solution to prevent it from happening that does not rely on any special coding in the Changed
event, I'd be happy with that too.