The binding value for the text box / checkbox is not valid until the checkbox is confirmed

I have a winforms checkbox tied to a property of an Entity Framework object.

So, for example, I have a bindingSource.DataSource = myDog flag attached to the IsSleeping property, so when the user checks this field, IsSleeping becomes true, and when the user IsSleeping , IsSleeping becomes false.

It works great. The problem is that the IsSleeping value IsSleeping not updated until the flag is checked, which happens only when the focus moves from the flag to another. Thus, if I want something to happen when the field is not checked:

 private void IsSleepingCheckbox_CheckedChanged(object sender, EventArgs e) { OnDogPropertyChanged(myDog); MyAnimalEntities.SaveChanges(); } 

myDog.IsSleeping will still be true until the Validated checkbox is checked. So when poor myNaughtyKitty (who is listening to the DogPropertyChanged event) comes to eat from myDog thinking for the food that myDog sleeping, myDog really just wakes up! Oh no!

Even worse, MyAnimalEntities.SaveChanges() does not yet see the changes in myDog , so the value of IsSleeping never stored in the database. Moving the .SaveChanges() call to IsSleepingCheckbox_Validated does not solve this problem, because if the flag is switched, but then the form closes without even moving the focus from the flag, the flag is never checked and therefore its state is never saved!

I suppose this should be a fairly common problem with data binding and checkboxes / text fields, and indeed, I found a ton of posts on this subject on the Internet, but no one ever has a solution. Has anyone been able to find a workaround for this?

+6
c # data-binding winforms entity-framework
source share
2 answers

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 this check box. Unfortunately, the CheckedChanged event still fires before updating the data source.

To handle this, you can handle the BindingSource.ListChanged event and move the 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); 

NTN

+7
source share

This is the right way to do this job. Handle CheckBox Verified Event

  /// <summary> /// Handles Check Box State if Changed /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void checkBoxBidSummaryItem_Validated(object sender, EventArgs e) { // Code to execute... _MyEntity.Save(_businessObject.SelectedBid); } 
-one
source share

All Articles