Ask To Save
There are several times when we need to ask the user if they want to save.
- When they select New from either the menu or tool strip,
- When they select Open from either the menu or tool strip,
- When they select Exit from the menu, or try to close the program using the X at the top right corner.
We need to make sure that we know if there are any changes: Click on the rich text box and add the code below:
private void richTextBox1_TextChanged(object sender, EventArgs e)
{
// Set change to true if there are any changes to the rich text box.
changed = true;
}
Write the code for AskToSave as shown below:
private Boolean AskToSave()
{
// If there is no change to rich text box don't ask, don't save, and don't cancel
DialogResult result= DialogResult.No;
if (changed)
{
result = MessageBox.Show("Do you want to save changes to " + currentFileName + "?", "Closing", MessageBoxButtons.YesNoCancel);
// If they answer yes, write the file
if (result == DialogResult.Yes) SaveFile();
}
// Returns true if they selected cancel.
// Returns false if there has been no change.
return (result== DialogResult.Cancel);
}
To Do: Think about when you would call this.
End of lesson, Next lesson: That is the last C# lesson in this course.