Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
468 views
Welcome To Ask or Share your Answers For Others

1 Answer

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();
  }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...