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?