Message box with “Yes”, “No” choices in C#?

18,415

Solution 1

If it's in main form close method you can use it like this:

private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
    if (MessageBox.Show("Really close?", "Exit", MessageBoxButtons.YesNo) ==
        System.Windows.Forms.DialogResult.No)
        e.Cancel = true;
}

If user press "Yes" your form will be closed due to no close cancellation. If it is not main form close doesn't mean application exit. In this case you can close parent form explicitly after ShowDialog call.

Solution 2

Below is code to prompt message (Yes/No):

DialogResult dialogResult = MessageBox.Show("Are you sure to delete Yes/No", "Delete", MessageBoxButtons.YesNo);

if (dialogResult == DialogResult.Yes)
{
   /// do something here        
}

Solution 3

Call Application.DoEvents() before Application.Exit(). But it is better to close parent form with Close() instead of Application.Exit.

Share:
18,415
Y.Arsoy
Author by

Y.Arsoy

Updated on June 25, 2022

Comments

  • Y.Arsoy
    Y.Arsoy almost 2 years

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

    DialogResult dialog = MessageBox.Show("Etes vous sûre de vouloir fermer le programme ?", "Exit",MessageBoxButtons.YesNo);
    if (dialog == DialogResult.Yes)
    {
      Application.Exit();
    }
    else if (dialog == DialogResult.No)
    {
        e.Cancel = true;
    }
    

    The problem is, when I click the YES Button, the popup does not close automatically. It will be closed after I click 2 times again. It should be closed from the first time.

    It seems pretty easy but I'm not sure where is my mistake;

  • i486
    i486 about 8 years
    Please explain the difference between No and Cancel.
  • Peter Szekeli
    Peter Szekeli about 8 years
    Why should it solve the problem? You only refactored the if to a switch. There's no other change, or do I miss something?
  • Ahmed Noozan Ali
    Ahmed Noozan Ali about 8 years
    i am sorry if it didnt ans ur question. but this is how i use it,, and it wrked for me..