views:

12

answers:

1

This is a winform C# problem.

I have an data object, say, Person. It has a property called Age and if Age is set to a negative value an exception will be thrown from its property setter.

On the form, the Age property is bound to a textbox using:

var binding = tbAge.DataBindings.Add("Text", person, "Age", true, DataSourceUpdateMode.OnValidation);

In order to discover the error, I create an BindingComplete event listener and test the BindingCompleteState against BindingCompleteState.Success and show necessary error message to the user.

That is all the background. Now, if I set a negative value on the textbox and DIRECTLY click the X button on the right top of the form to close it, the expected error message shows but the form is not closed.

I want the form to be closed and don't care if the error message is shown or not in this case. The validation part is preferred not to be altered. I don't want to hide the X button and put a close button on the form manually. Is there any right way to achieve my purpose? Thank you very much for any help.

+1  A: 

I just found a solution.

Though I still remain unknown the reason why the form is prevented from closing, I guess it has something to do with the exception I throw from the data object and some validation of the form. (Please correct me if I am wrong.)

Disable AutoValidate of the form is not a solution. Since then my error message will not be shown.

What I do is implement the IDataErrorInfo for the Person class. Normally the textbook tells that IDataErrorInfo works with some ErrorProvider UI component to show the red circle next to the control. We don't use ErrorProvider at all. But IDataErrorInfo is still useful because the BindingCompleteState will still be set to proper status. So IDataErrorInfo acts as a bridge between my data object and the bindingsource, to pass underlying data level errors to surface. Then the bindingcomplete event does the same thing.

The key of using IDataErrorInfo is now I can close my form without any problem. I still don't know why but without the exception being thrown from data object, the form can close itself properly. Let me know what is the reason to prevent the form from closing in my problem.

Steve