We have created an Application called Notes with a rich text box
Next we will write the code to load a file into the richtext box when the user selects open from the menu or when they click the open button on the toolbar.
Write the code as shown below, selecting each event from either the properties window, or clicking the item on the form:
private void OpenFile()
{
// Remind to save.
Boolean cancel = AskToSave();
// If user did not select cancel, continue.
if (!cancel)
{
// Set the filter. This could be done once in form load.
openFileDialog1.Filter = "RichText|*.rtf";
// Set default to current file
openFileDialog1.FileName = currentFileName;
openFileDialog1.ShowDialog();
// If the user selects cancel filename will be "".
if (openFileDialog1.FileName != "")
{
// Load the new file
richTextBox1.LoadFile(openFileDialog1.FileName);
// There have been no changes since the last save.
changed = false;
// track current filename.
currentFileName = openFileDialog1.FileName;
// Display the filename in the status bar.
toolStripStatusFilename.Text = openFileDialog1.FileName;
}
}
}
private void openToolStripMenuItem_Click(object sender, EventArgs e)
{
// OpenFile is called from both the menu item and tool strip button.
OpenFile();
}
private void openToolStripButton_Click(object sender, EventArgs e)
{
// OpenFile is called from both the menu item and tool strip button.
OpenFile();
}
Click Save All at this point and run the program.
Open the file that you created earleir, then click save. Although we just opened the file, it prompts us for the location to save the file.
Test, test, test! Test every menu and toolbar button at this point.
Click Save All at this point.
End of lesson, Next lesson: That is the last C# lesson in this course.