user3609114
user3609114

Reputation:

Message box closes form regardless of result

i am new to message box buttons and it seems to close the form regardless.

private void btnFechar_Click(object sender, EventArgs e)
{
    DialogResult = MessageBox.Show("Desjea Sair?", "Aviso", MessageBoxButtons.YesNo, MessageBoxIcon.Question);

    if (DialogResult == DialogResult.Yes)
    {
        this.Close();
    }
}

thanks in advance

Upvotes: 0

Views: 91

Answers (1)

Grant Winney
Grant Winney

Reputation: 66469

You're setting the DialogResult of the form (this looks like WinForms), which always closes it.

Create a local variable inside your button click event:

private void btnFechar_Click(object sender, EventArgs e)
{
    var dialogResult = MessageBox.Show("Desjea Sair?", "Aviso", MessageBoxButtons.YesNo, MessageBoxIcon.Question);

    if (dialogResult == DialogResult.Yes)
    {
        this.Close();
    }
}

More on Form.DialogResult from MSDN:

If the form is displayed as a dialog box, setting this property with a value from the DialogResult enumeration sets the value of the dialog box result for the form, hides the modal dialog box, and returns control to the calling form.

So if you're displaying the form using ShowDialog() as most of us do, then setting the form's DialogResult property causes it to close.

Upvotes: 4

Related Questions