Microsoft Visual Studio - Notepad

Hemanth B 886 Reputation points
2021-05-22T07:07:52.327+00:00

Hi, I recently created a notepad using Visual studio 2019. I added a save button to the notepad. Now how shall I code this:

When the user saves their file for the first time, the user selects their desired location in Windows, and once they save it in a location and continue editing their file, the save button again opens up the "Save as" dialog box. Is there any way that once the user saves their file for the first time and again edits it, it does not open up the "Save as" dialog box. And is there any way that if the user edits their file and clicks the close app button on top right without saving their changes, a dialog box appears saying: "Do you want save changes to your file"?

Developer technologies C#
0 comments No comments
{count} votes

Accepted answer
  1. Sam of Simple Samples 5,546 Reputation points
    2021-05-22T18:10:30.757+00:00

    I think this will do everything you are asking. Please test thoroughly.

    public partial class Form1 : Form
    {
        string Filename = null;
        string Previous = string.Empty;
    
        public Form1()
        {
            InitializeComponent();
        }
    
        private void exitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Close();
        }
    
        private void saveAsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (SaveAs())
            {
                Previous = textBox1.Text;
            }
        }
    
        /// <summary>
        /// Saves to a file selected by the user
        /// </summary>
        /// <returns>true if something was saved</returns>
        private bool SaveAs()
        {
            SaveFileDialog sfd = new SaveFileDialog();
            sfd.Filter = "Text file|*.txt|All files|*.*";
            sfd.Title = "Save a text file";
            if (sfd.ShowDialog() != DialogResult.OK)
                return false;
            if (sfd.FileName == "")
                return false;
            try
            {
                using (StreamWriter sw = new StreamWriter(sfd.FileName))
                {
                    sw.Write(textBox1.Text);
                    Filename = sfd.FileName;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Write error: " + ex.Message);
                return false;
            }
            return true;
        }
    
        private void saveToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (Save())
            {
                Previous = textBox1.Text;
            }
        }
    
        /// <summary>
        /// Saves to the file; calls SaveAs if no previous file 
        /// </summary>
        /// <returns>true if something was saved</returns>
        private bool Save()
        {
            if (Filename == null)
            {
                bool saved = SaveAs();
                if (saved)
                {
                    Previous = textBox1.Text;
                }
                return saved;
            }
            try
            {
                using (StreamWriter sw = new StreamWriter(Filename))
                {
                    sw.Write(textBox1.Text);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Write error: " + ex.Message);
                return false;
            }
            return true;
        }
    
        private void closeToolStripMenuItem_Click(object sender, EventArgs e)
        {
            AskToSave();
        }
    
        private void AskToSave()
        {
            if (textBox1.Text == Previous)
            {
                Filename = null;
                return;
            }
            DialogResult dr = MessageBox.Show(
                "Do you wish to save changes?",
                "Unsaved changes",
                MessageBoxButtons.YesNo,
                MessageBoxIcon.Question
                );
            if (dr != DialogResult.Yes)
                return;
            Save();
            Previous = string.Empty;
            Filename = null;
        }
    
        private void openToolStripMenuItem_Click(object sender, EventArgs e)
        {
            OpenFileDialog ofd = new OpenFileDialog();
            ofd.Filter = "Text file|*.txt|All files|*.*";
            if (ofd.ShowDialog() != DialogResult.OK)
                return;
            try
            {
                using (StreamReader sr = new StreamReader(ofd.FileName))
                {
                    Previous = sr.ReadToEnd();
                    textBox1.Text = Previous;
                    Filename = ofd.FileName;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Read error: "+ex.Message);
            }
        }
    
        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            AskToSave();
        }
    }
    

2 additional answers

Sort by: Most helpful
  1. Karen Payne MVP 35,586 Reputation points Volunteer Moderator
    2021-05-22T10:52:07.38+00:00

    Here is a mockup which uses a private variable that would in your case know if there are unsaved changes. A CheckBox allow simulation of if a prompt is needed on form closing event.

    using System;
    using System.ComponentModel;
    using System.Windows.Forms;
    using static WindowsFormsApp1.Dialogs;
    
    namespace WindowsFormsApp1
    {
        public partial class Form1 : Form
        {
            public Form1()
            {
                InitializeComponent();
                Closing += OnClosing;
            }
    
            private void OnClosing(object sender, CancelEventArgs e)
            {
                if (!_hasChanges) return;
    
                if (Question("Save changes?"))
                {
                    e.Cancel = true;
                }
    
            }
    
            private bool _hasChanges;
            private void checkBox1_CheckedChanged(object sender, EventArgs e)
            {
                _hasChanges = checkBox1.Checked;
            }
        }
    }
    

    MessageBox wrapper (optional, you can do it your way) which defaults to the No button.

    using System.Windows.Forms;
    
    namespace WindowsFormsApp1
    {
        public static class Dialogs
        {
            public static bool Question(string text) => 
            (
                MessageBox.Show(text, "Question", 
                    MessageBoxButtons.YesNo, MessageBoxIcon.Question, 
                    MessageBoxDefaultButton.Button2) == DialogResult.Yes);
    
        }
    }
    

  2. Artemiy Moroz 271 Reputation points
    2021-05-22T17:05:54.643+00:00

    hi there!

    The idea is that you need to create a variable called "SavedFlag" in your program. For new file you set SavedFlag to false. Once the user saves the text, you set the SavedFlag to true. Upon pressing "Save" button, you check the SavedFlag. If it is already true, then you just write the file. If the flag is false, you call the SaveFileDialog procedure.

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.