Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Data Binding and throwing exception in setter

Let's 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 setup a binding for this class:

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

Now if I enter incorrect age value in the text box (say 200) the exception in the setter will be swallowed and I will not be able to do anything at all until I correct the value in the textbox. I mean the textbox will not be able to loose focus. It's all silent - no errors - you just can't do anything (even close the form or the whole application) until you correct the value.

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

like image 351
nightcoder Avatar asked May 18 '09 23:05

nightcoder


1 Answers

Ok, here is the solution:

We need to handle BindingComplete event of BinsingSource, CurrencyManager or BindingBanagerBase class. The code can look like this:

/* 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();
  }
}
like image 61
nightcoder Avatar answered Oct 08 '22 05:10

nightcoder