C# Validate before leaving accept_button event

南笙酒味 提交于 2019-12-23 09:23:37

问题


Excuse me if this is a silly question but i'm a beginer here.

I have a simply custom dialog with two buttons: Accept and Cancel. The Accept button is the acceptButton of the form.

I want to do some validations on the Accept_Click event and decide if i can close the dialog or not, but everytime it leaves this method, the dialog automatically closes itself and returns Ok.

What can I do to stop the dialog from closing itself? or i have to do things in some other way?

thanks


回答1:


I would have a form level variable (call it _vetoClosing) In the accept button's Click event, I would run validation and set the variable based on that:

    private void acceptButton_Click(object sender, EventArgs e)
    {
        // Am I valid
        _vetoClosing = !isValid();
    }

Then in the FormClosing event, I would cancel close if _vetoClosing is true

    private void Form_FormClosing(object sender, FormClosingEventArgs e)
    {
        // Am I allowed to close
        if (_vetoClosing)
        {
            _vetoClosing = false;
            e.Cancel = true;
        }
    }

Turning Accept button off is suboptimal because you loose the Enter to Press functionality.




回答2:


I would validate as the controls change, and only enable the Accept button if the whole form is valid.

This would allow you to keep your button as the default button (AcceptButton), but prevent this from occurring.




回答3:


A cleaner solution would be to set DialogResult to None:

private void acceptButton_Click(object sender, EventArgs e)
{
    if (!isValid()) {
        this.DialogResult = System.Windows.Forms.DialogResult.None;
    }
}



回答4:


Is the AcceptButton or CancelButton on the form set to that button? If so, try unsetting it and manually setting DialogResult in your handler when you want to close the dialog.



来源:https://stackoverflow.com/questions/784167/c-sharp-validate-before-leaving-accept-button-event

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