I have a winforms checkbox that is bound to a property of an Entity Framework entity.
So for example, I have bindingSource.DataSource = myDog
with a checkbox bound to the property IsSleeping
, so that when the user checks the box, IsSleeping
becomes true, and when the user unchecks the box, IsSleeping
becomes false.
This works fine. The problem is that the value of IsSleeping
is not updated until the checkbox is validated, which only occurs when focus moves away from the checkbox to something else. Thus, if I want something to happen when the box is unchecked:
private void IsSleepingCheckbox_CheckedChanged(object sender, EventArgs e)
{
OnDogPropertyChanged(myDog);
MyAnimalEntities.SaveChanges();
}
myDog.IsSleeping
will still be true, until the checkbox's Validated
is later raised. Thus, when poor myNaughtyKitty
(who is listening to the DogPropertyChanged
event) comes to eat out of myDog
's food dish thinking myDog
is sleeping, myDog
is really just waking up! Oh no!
Even worse, MyAnimalEntities.SaveChanges()
does not see the changes to myDog
yet, so the value of IsSleeping
is never saved to the database. Moving the .SaveChanges()
call to IsSleepingCheckbox_Validated
does not solve this problem, because if the checkbox is toggled but then the form is closed without ever moving focus away from the checkbox, the checkbox is never validated and thus its state is never saved!
I imagine this must be a fairly common problem with databinding and checkboxes/textboxes, and indeed I've found a ton of posts on the subject online, but no one ever seems to have a solution. Has anyone been able to find a workaround for this?
You can change the Binding.DataSourceUpdateMode property to OnPropertyChanged
(the default is OnValidation
), which will cause the data source to be updated when the user clicks the checkbox. Unfortunately, the CheckedChanged
event still fires before the data source is updated.
To deal with this, you can handle the BindingSource.ListChanged event and move your SaveChanges
code there.
bindingSource = new BindingSource();
bindingSource.DataSource = myDog;
checkBox1.DataBindings.Add(new Binding("Checked", bindingSource, "IsSleeping"));
checkBox1.DataBindings[0].DataSourceUpdateMode = DataSourceUpdateMode.OnPropertyChanged;
bindingSource.ListChanged += new ListChangedEventHandler(bindingSource_ListChanged);
HTH
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With