Home > Mobile >  e.Cancel does not work in C#. e.Cancel doesn't prevent form closing
e.Cancel does not work in C#. e.Cancel doesn't prevent form closing

Time:07-01

I am working on my C# project. When I click NO button in message box, it closes form, instead close messagebox itself. I think because e.Cancel = true doesnt't work.

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {           
            DialogResult savewrn = MessageBox.Show("Are you sure to quit? You didn'save your work.", "Before you quit", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2);
            if (_isSaved == false)
            {
                if(savewrn == DialogResult.No)
                {
                    e.Cancel = true;
                    //It closes form, maybe e.Cancel isn't work
                }
                else if (savewrn == DialogResult.Yes)
                {
                    e.Cancel = false;
                    this.Close();
                    Application.Exit();
                }
            }
            else
            {
                //Do nothing
            }

CodePudding user response:

I suggest to put ifs in different order:

private void Form1_FormClosing(object sender, FormClosingEventArgs e) {
  // If the data is saved, we should not ask any questions
  if (_isSaved)
    return;
  
  // If data is not saved we put a question
  // If answer in not "yes", i.e. it is "no" or "cancel" 
  // (when wuser just closes the message box)
  // we let the system to close the window  
  if (MessageBox.Show("Are you sure to quit? You didn'save your work.", 
                      "Before you quit", 
                       MessageBoxButtons.YesNo, 
                       MessageBoxIcon.Question, 
                       MessageBoxDefaultButton.Button2) != DialogResult.Yes)
    return;

  // Only if the data is not saved and user answered "yes" we cancel closing
  // .. or you may want to save the data and don't cancel 
  e.Cancel = true;
}
  • Related