Ask user to save before closing then exit the winform application

ravi kumar 331 Reputation points
2022-04-26T10:48:00.46+00:00

My below code should ask the user before closing the form, if no then exit the application itself.

private void DataEntry_FormClosing(object sender, FormClosingEventArgs e)  
    {  
        try  
        {  
            String msg = "Confirm Save?";  
            String caption = "Save Record";  
            MessageBoxButtons buttons = MessageBoxButtons.YesNo;  
            MessageBoxIcon ico = MessageBoxIcon.Question;  
            DialogResult result;  
            result = MessageBox.Show(this, msg, caption, buttons, ico);  
            if (result == DialogResult.Yes)  
            {  
                this.Validate();  
                this.tool_ManagementBindingSource.EndEdit();  
                this.tableAdapterManager.UpdateAll(this.pINQCDataSet);  
                MessageBox.Show("The Record saved Successfully", "Save_Update",  
                    MessageBoxButtons.OK, MessageBoxIcon.Information);  
  
            }  
            else  
            {  
                Application.Exit();   
            }  
        }  
        catch (Exception ex)  
        {  
            MessageBox.Show("Saving Failed:" + ex.Message.ToString(), "Save",  
                MessageBoxButtons.OK, MessageBoxIcon.Error);  
        }  
    }  

But I am getting message box appeared twice even after clicking no , then the below error appears , please guide me how to solve this problem.
@Karen Payne MVP :pls help me.

196536-image.png

Windows Forms
Windows Forms
A set of .NET Framework managed libraries for developing graphical user interfaces.
1,820 questions
{count} votes

2 answers

Sort by: Most helpful
  1. Akram Elhayani 1 Reputation point
    2022-05-23T19:07:43.23+00:00

    Use

    e.Cancel = true ;
    

    instead of

    Application.Exit( )
    

    then in FormClosed try call

      Application.ExitThread();
    

  2. Karen Payne MVP 35,031 Reputation points
    2022-05-23T20:53:05.727+00:00

    Greetings, I took an existing code sample, added code to detect changes and then prompt for exit without saving or save and close.

    It uses MS-Access but does not matter as all that matters is the DataTable in the DataSet.

    Source code

    Form code

    using System;
    using System.ComponentModel;
    using System.Windows.Forms;
    using Access1.Classes;
    using static Access1.Classes.Dialogs;
    
    namespace Access1
    {
        public partial class Form1 : Form
        {
            public Form1()
            {
                InitializeComponent();
                Closing += OnClosing;
            }
    
            private void OnClosing(object sender, CancelEventArgs e)
            {
                if (dataSet1.Tables[0].HasChanges())
                {
                    if (Question("Save before exiting"))
                    {
                        SaveChanges();
                    }
                    else
                    {
                        e.Cancel = false;
                    }
                }
    
            }
    
            private void personBindingNavigatorSaveItem_Click(object sender, EventArgs e)
            {
                SaveChanges();
            }
    
            private void SaveChanges()
            {
                Validate();
                personBindingSource.EndEdit();
                tableAdapterManager.UpdateAll(dataSet1);
            }
    
            private void Form1_Load(object sender, EventArgs e)
            {
                personTableAdapter.Fill(dataSet1.Person);
            }
        }
    }
    

    MessageBox

    public static class Dialogs
    {
        public static bool Question(string text)
        {
            return (MessageBox.Show(
                text,
                Application.ProductName,
                MessageBoxButtons.YesNo,
                MessageBoxIcon.Question,
                MessageBoxDefaultButton.Button2) == DialogResult.Yes);
        }
    }
    

    Detect changes (can be optimize, wrote it fast)

    public static class ExtensionMethods
    {
        public static bool HasChanges(this DataTable table)
        {
            var added = table.GetChanges(DataRowState.Added);
            if (added != null)
            {
                return true;
            }
    
            var deleted = table.GetChanges(DataRowState.Deleted);
            if (deleted != null)
            {
                return true;
            }
    
            var modified = table.GetChanges(DataRowState.Modified);
            if (modified != null)
            {
                return true;
            }
    
            return false;
        }
    
    }
    
    0 comments No comments