2

i want a message box to ask for unsaved data on Form closing Event.

if the user choose yes then save the data in text file and exit application.

if the user choose no exit application without saving.

i have tried the following code.But it does not close the application and make message box appear again and again.

  public void SaveMyFile()
    {
        //// Create a SaveFileDialog to request a path and file name to save to.
        SaveFileDialog saveFile1 = new SaveFileDialog();

        //// Initialize the SaveFileDialog to specify the RTF extension for the file.
        saveFile1.DefaultExt = "*.txt";
        saveFile1.Filter = "Info Changed Data (*.txt)|*.txt";

        //// Determine if the user selected a file name from the saveFileDialog. 
        if (saveFile1.ShowDialog() == System.Windows.Forms.DialogResult.OK &&
           saveFile1.FileName.Length > 0)
        {
            //// Save the contents of the RichTextBox into the file.
            richTextBox1.SaveFile(saveFile1.FileName, RichTextBoxStreamType.PlainText);
        }
    }

    private void Form1_FormClosing(object sender, FormClosingEventArgs e)
    {
        DialogResult dialogResult = MessageBox.Show("Do You Want To Save Your Data", "CodeJuggler", MessageBoxButtons.YesNo);
        if (dialogResult == DialogResult.Yes)
        {
            SaveMyFile();
            this.Close();
        }
        else if (dialogResult == DialogResult.No)
        {
            this.Close(); 
        }
    }
Vy Do
  • 46,709
  • 59
  • 215
  • 313
swagger
  • 37
  • 1
  • 9

2 Answers2

7

Delete the line

this.Close();

it is not necessary. It should be like this:

private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
    DialogResult dialogResult = MessageBox.Show("Do You Want To Save Your Data", "CodeJuggler", MessageBoxButtons.YesNo);
    if (dialogResult == DialogResult.Yes)
    {
        SaveMyFile();
    }
}

Or like this:

    private void Form1_FormClosing(object sender, FormClosingEventArgs e)
    {
        DialogResult dialogResult = MessageBox.Show("Do You Want To Save Your Data", "CodeJuggler", MessageBoxButtons.YesNoCancel);
        if (dialogResult == DialogResult.Yes) SaveMyFile();
        else if (dialogResult == DialogResult.Cancel) e.Cancel = true;
    }
Vojtěch Dohnal
  • 7,867
  • 3
  • 43
  • 105
0

"... again and again" without a loop is usually a hint that there is some recusion in the program.

In your case you call Form.Close() inside the Closing event handler, which then raises the Closing event in which you call Form.Close() and ... I think you get it.

Simply remove the calls to Close(), you don't need them. If Closing is raised then your form will be closed unless you set the Cancel property in the FormClosingEventArgs parameter to true.

Dirk
  • 10,668
  • 2
  • 35
  • 49