Data exclusion and setter throw exclusion

Say I have a simple class

public class Person
{
  public string Name { get; set; }

  private int _age;
  public int Age
  {
    get { return _age; }
    set
    {
      if(value < 0 || value > 150)
        throw new ValidationException("Person age is incorrect");
      _age = value;
    }
  }
}

Then I want to set the binding for this class:

txtAge.DataBindings.Add("Text", dataSource, "Name");

Now, if I enter the wrong age value in the text box (say 200), the setter exception will be swallowed, and I can’t do anything until I correct the value in the text box. I mean, the text box cannot lose focus. All silence - no mistakes - you just can’t do anything (even close the form or the entire application) until you correct the value.

It seems like a mistake, but the question is, what is the workaround for this?

+5
source share
1 answer

Ok, here is the solution:

BindingComplete BinsingSource, CurrencyManager BindingBanagerBase. :

/* Note the 4th parameter, if it is not set, the event will not be fired. 
It seems like an unexpected behavior, as this parameter is called 
formattingEnabled and based on its name it shouldn't affect BindingComplete 
event, but it does. */
txtAge.DataBindings.Add("Text", dataSource, "Name", true)
.BindingManagerBase.BindingComplete += BindingManagerBase_BindingComplete;

...

void BindingManagerBase_BindingComplete(
  object sender, BindingCompleteEventArgs e)
{
  if (e.Exception != null)
  {
    // this will show message to user, so it won't be silent anymore
    MessageBox.Show(e.Exception.Message); 
    // this will return value in the bound control to a previous correct value
    e.Binding.ReadValue();
  }
}
+3

All Articles