Andrew De Forest
Andrew De Forest

Reputation: 7368

MessageBoxResult vs. DialogResult

Two questions here, hope that is OK.

First, and mainly, I am trying to prompt the user when they exit my application whether or not they really want to exit. My code is as follows:

private void exitToolStrip_Click(object sender, EventArgs e)
{
    DialogResult mBoxResult = MessageBox.Show("Would you like to exit the program?", "Exit Program", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
    switch (mBoxResult)
    {
        case DialogResult.Yes:
            this.Close();
            break;
        case DialogResult.No:
            break;
    }
}

According to MSDN, I should be using MessageBoxResult mBoxResult rather than DialogResult mBoxResult.

I am using .NET Framework 3.5. I read here that pre-3.0 should use DialogResult, but if I’m using 3.5, shouldn't MessageBoxResult work?

When I try to call it, I get

The type or namespace name MessageBoxResult could not be found (are you missing a using directive or an assembly reference?).

However, it works fine when I use DialogResult. Why is this?

My second question is regarding this piece of code:

case DialogResult.No:
break;

If somebody hits the Cancel button on the dialog, would it be proper to put anything in there besides the break? Or will everything function fine without it?

Upvotes: 8

Views: 10260

Answers (2)

ken2k
ken2k

Reputation: 48985

As you can see, namespaces are different: System.Windows.Forms (Winforms) vs System.Windows (WPF).

Upvotes: 8

Igby Largeman
Igby Largeman

Reputation: 16747

DialogResult is for WinForms. MessageBoxResult is for SilverLight.

Just the break statement is fine for the No case. But using a switch statement is overkill here. if (response == yes) Close(); would suffice.

Note however that this isn't an ideal way to do what you want. What if the user clicks the close button on the window border, or presses ALT+F4? Instead, you should handle the FormClosing event:

private void MyForm_FormClosing(object sender, FormClosingEventArgs e)
{
    if (MessageBox.Show("Would you like to exit the program?", "Exit Program", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
        e.Cancel = true;
}

By setting e.Cancel to true, you cancel the closure of the form. By doing nothing, you allow the form to close.

Upvotes: 11

Related Questions