Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to stop the execution of DialogResult based on a condition?

I'm having a issue with the following scenario on Windows Forms:

I created a Form with two buttons, each button have been assigned with the behaviour DialogResult OK and DialogResult Cancel, respectively. But based on certain conditions, I need to stop the execution of the OK button. The problem is that if I just made a return like this:

private void btnOk_Click(object sender, EventArgs e)
    {
        foreach(Control control in tblTable.Controls)
        {
            if (control.GetType() == typeof(TextBox))
            {
                 if (control.Text.Trim() == "")
                 {
                     control.Focus(); return;
                 }
            }
            else
            {

            }
        }
    }

The dialog result keeps returning the OK answer to the parent form.

I need to stop the execution of the event and not return any answer until the user corrects the info on the form. In other words, the user should be taken back to the form to correct any missing or wrong data.

like image 833
lidermin Avatar asked Aug 10 '10 16:08

lidermin


2 Answers

As Hans Passant mentions in an comment, just set the DialogResult to None!
Like this:

private void btnOk_Click(object sender, EventArgs e)
{
    if(ValidationFailed())
    {
        this.DialogResult = DialogResult.None;
        return;
    }
    //...
}
like image 106
Ulf Åkerstedt Avatar answered Jan 02 '23 20:01

Ulf Åkerstedt


Personally I wouldn't use DialogResults on buttons in this scenario. I only tend to set the DialogResult when there's only distinct options that do not require any additional logic (i.e. making a custom MessageBox).

What I would do is to just send the DialogResult yourself on success:

private void btnOk_Click(object sender, EventArgs e)
{
    if (allIsOK())
    {
        this.DialogResult = DialogResult.OK;
    }
}
like image 44
djdd87 Avatar answered Jan 02 '23 20:01

djdd87