Cancel validation event on custom UserControl when form closing

瘦欲@ 提交于 2019-12-23 01:51:16

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!