Click here to Skip to main content
15,891,372 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
i have a richtext box

i want to ask the user to save that data in richtext box on form closing event.

C#
protected override void OnFormClosing(FormClosingEventArgs e) 
{
        base.OnFormClosing(e);
        if (!e.Cancel) {
            if (MessageBox.Show("Really?", "Close", MessageBoxButtons.YesNo) != DialogResult.Yes) 

            {
                e.Cancel = true;
            }
        }
    }


above is the code for asking user on closing event.

My code for saving richtextbox data in txt file is

C#
<pre lang="cs">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 = "Chat History (*.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);
            }
        }



if user says yes then save file and exit

if user says no then exit without saving.
Posted

1 solution

The normal approach here would be three choices - Save? yes/no/cancel

Anyway for your approach try:

C#
protected override void OnFormClosing(FormClosingEventArgs e) 
{
        base.OnFormClosing(e);
        if (!e.Cancel) {
            if (MessageBox.Show("Do you want to save changes?", "Close", MessageBoxButtons.YesNo) != DialogResult.Yes) 
 
            {
                // e.Cancel = true;
                SaveMyFile();
            }
        }
    }
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900