Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MessageBoxResult vs. DialogResult

Tags:

c#

.net

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?

like image 621
Andrew De Forest Avatar asked Feb 10 '12 16:02

Andrew De Forest


2 Answers

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.

like image 139
Igby Largeman Avatar answered Nov 04 '22 13:11

Igby Largeman


  • Use DialogResult if your application is a WinForms application
  • Use MessageBoxResult if your application is a WPF/Silverlight application

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

like image 21
ken2k Avatar answered Nov 04 '22 13:11

ken2k