c# AcceptButton and validation

exMode picture exMode · Sep 26, 2010 · Viewed 20.2k times · Source

Hi I have a form which contains of several textboxes and two buttons Cancel and Ok. These buttons are assigned to accept and cancel buttons properties in form. The problem is that I have to validate texts entered in all textboxes.

I want to do that if user click Ok button(which is acceptButton). So I wrote a function which is reponsible for validation and I fire this function if user click Ok button. The problem is that I can't stop form from closing even if validation function return false. It happens because of the fact that I assigned acceptbutto property to my Ok button. Is there any way to prevent form from closing if validation fails without removing acceptbutton properties ??

Answer

Alex from Jitbit picture Alex from Jitbit · Jun 28, 2011

This is the working solution we use (and it's kinda compiled from other answers).

You just have to set the DialogResult to None to prevent the form from closing.

//form init, auto-generated code (this is the case described)
private void InitializeComponent()
{
    //....
    this.AcceptButton = btnOk;
    this.btnOk.DialogResult = DialogResult.OK;
    //....
}

//event handlers
private void btnOK_Click(object sender, EventArgs e)
{
    if (!Validate())
        this.DialogResult = DialogResult.None;
}

private void Form_FormClosing(object sender, FormClosingEventArgs e)
{
    if (this.DialogResult == DialogResult.None)
        e.Cancel = true;
}