tags:

views:

16

answers:

2

Hello,

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 condition 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 don't return any answer until the user correct the info on the form.

Thanks for your help.

+1  A: 

Consider tapping into the Forms's Closing event, and use the Cancel property of the event args to cancel form closing.

Here's a web page that discusses the idea; it's VB, but you'll get the idea:

http://www.vbinfozine.com/t_wfdlg.shtml

kbrimington
+1  A: 

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;
    }
}
GenericTypeTea
I agree with you, this is the more clean solution. Thanks for your answer.
lidermin
I don't. Windows UI design demands that the dialog closes when the user presses the Enter key and that the default button (OK) is marked. The workaround is simple, just set the DialogResult to None.
Hans Passant