C# MessageBox dialog result

前端 未结 5 1229
心在旅途
心在旅途 2021-01-30 04:17

I want to make a MessageBox confirmation. Here is the message box:

MessageBox.Show(\"Do you want to save changes?\", \"Confirmation\", messageBoxButtons.YesNoCan         


        
相关标签:
5条回答
  • 2021-01-30 04:26

    This answer was not working for me so I went on to MSDN. There I found that now the code should look like this:

    //var is of MessageBoxResult type
    var result = MessageBox.Show(message, caption,
                                 MessageBoxButtons.YesNo,
                                 MessageBoxIcon.Question);
    
    // If the no button was pressed ... 
    if (result == DialogResult.No)
    {
        ...
    }
    

    Hope it helps

    0 讨论(0)
  • 2021-01-30 04:28
    DialogResult result = MessageBox.Show("Do you want to save changes?", "Confirmation", MessageBoxButtons.YesNoCancel);
    if(result == DialogResult.Yes)
    { 
        //...
    }
    else if (result == DialogResult.No)
    { 
        //...
    }
    else
    {
        //...
    } 
    
    0 讨论(0)
  • 2021-01-30 04:35

    You can also do it in one row:

    if (MessageBox.Show("Text", "Title", MessageBoxButtons.YesNo) == DialogResult.Yes)
    

    And if you want to show a messagebox on top:

    if (MessageBox.Show(new Form() { TopMost = true }, "Text", "Text", MessageBoxButtons.YesNo) == DialogResult.Yes)
    
    0 讨论(0)
  • 2021-01-30 04:40

    Rather than using if statements might I suggest using a switch instead, I try to avoid using if statements when possible.

    var result = MessageBox.Show(@"Do you want to save the changes?", "Confirmation", MessageBoxButtons.YesNoCancel);
    switch (result)
    {
        case DialogResult.Yes:
            SaveChanges();
            break;
        case DialogResult.No:
            Rollback();
            break;
        default:
            break;
    }
    
    0 讨论(0)
  • 2021-01-30 04:46

    If you're using WPF and the previous answers don't help, you can retrieve the result using:

    var result = MessageBox.Show("Message", "caption", MessageBoxButton.YesNo, MessageBoxImage.Question);
    
    if (result == MessageBoxResult.Yes)
    {
        // Do something
    }
    
    0 讨论(0)
提交回复
热议问题