问题
I have a custom control that gets focus when the form is loaded. It uses validating event on it that handles it being left empty or having invalid data entered.
My problem is, when the user loads the form, then just closes it, it is going through the validation process and displaying errors because it is left empty.
On the BaseForm (: Form) we have overwritten the WndProc method and set a flag on the form to say it is closing, now in the validating event handler I can get the parent form and cancel return from the method if the form is closing.
What I am wanting to do it perform this check on the object so it affected all of the existing instances and cancels the validating events when the form is closing. I just cannot get the event to cancel.
Here is a shell of the UserControl Code.
public class SearchControl : UserControl
{
public SearchControl()
{
Validating += OnControlValitading;
}
public void OnControlValitading(object sender, CancelEventArgs e)
{
BaseForm frm = FindForm() as BaseForm;
if(frm != null && frm.IsClosing)
{
e.Cancel = true;
//TODO Cancel validation event on all objects
}
}
}
回答1:
Override OnValidating and use the CancelEventArgs:
public class SearchControl : UserControl
{
protected override void OnValidating(CancelEventArgs e)
{
BaseForm frm = FindForm() as BaseForm;
if (frm != null && frm.IsClosing)
{
e.Cancel = true;
//TODO Cancel validation event on all objects
}
}
}
来源:https://stackoverflow.com/questions/12790706/cancel-validation-event-on-custom-usercontrol-when-form-closing