0

I making a C# Windows Forms Application. I'm trying to have a message box popup when the "X" or Close Button is pressed to exist out of the application. This is what I have so far, and I don't know whats wrong with it. When I run the message box doesn't show up when I click on the Close Button. Any help would be appreciated. Thanks.

private void MainWindow_FormClosing(object sender, FormClosingEventArgs e)
{
    if (this.DialogResult == DialogResult.Cancel)
    {
        if (MessageBox.Show("Do you want to save changes to the data?",
                            "MktAuthorizationData", 
                            MessageBoxButtons.YesNo) == DialogResult.Yes)
        {
            e.Cancel = true;
            // Do Something 
        }
    }
}
4
  • 1
    Did you bind the event handler code to the Form_Closing event?
    – Steve
    Apr 27, 2016 at 13:31
  • 1
    Are you positive that this method is bound to the FormClosing event for MainWindow?
    – AntiTcb
    Apr 27, 2016 at 13:32
  • I don't know what that means. I don't think so and how would I go about doing that.
    – Satish
    Apr 27, 2016 at 13:34
  • Thank You very much it works now
    – Satish
    Apr 27, 2016 at 13:37

2 Answers 2

6

You need to remove below condition

if (this.DialogResult == DialogResult.Cancel)

The below code should work

private void MainWindow_FormClosing(object sender, FormClosingEventArgs e)
{
    if (MessageBox.Show("Do you want to save changes to the data?",
                        "MktAuthorizationData", 
                        MessageBoxButtons.YesNo) == DialogResult.Yes)
    {
            e.Cancel = true;
            // Do Something 
    }
}

In case you haven't subscribed to the event you need to do this by having this after InitializeComponent();

this.FormClosing += MainWindow_FormClosing;
0
0

You can add a Button Close event to close your window form with message box.

private void btnClose_Click(object sender, EventArgs e)
    {        

   if (MessageBox.Show("Do you want to save changes to the data?",
                    "MktAuthorizationData", 
                    MessageBoxButtons.YesNo) == DialogResult.Yes)
       {
        e.Cancel = true;
        // Do Something 
       }
   } 

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.