Zebra0.com

csharp richtext

We have created an Application called Notes with a rich text box, a menu with standard items, a toolstrip and a status strip.
The rich text box fills the form.

Because the RichText format is a proprietary Microsoft format, it is not likely that you have any RTF files to open, so we must create some text and save it so that we have a file to open.

We will write the code to save the contents of the richtext box when the user selects save from the menu or when they click the save button on the toolbar.
We will write the function saveFile, then call if from both of these events..

  1. Continue with the Notes Application.
  2. Set the Filter property to RichText|*.rtf
  3. Write the code as shown below:
private void SaveFile()
{
   // Make the save file name the same as open file.
   saveFileDialog1.FileName = openFileDialog1.FileName;
   if (currentFileName == "Untitled")
   {
      saveFileDialog1.Filter = "RichText|*.rtf";
      saveFileDialog1.ShowDialog();
      // If user selected cancel filename will be "".
      if (saveFileDialog1.FileName != "")
      {
         currentFileName = saveFileDialog1.FileName;
      }
   }
   if (currentFileName != "Untitled")
   {
      // Save the file.
      richTextBox1.SaveFile(saveFileDialog1.FileName);
      // There have been no changes since the last save.
      changed = false;
      // Display the filename in the status bar.
      toolStripStatusFilename.Text = saveFileDialog1.FileName;
    }
}
        
private void saveToolStripButton_Click(object sender, EventArgs e)
{
  // Save the file.
  SaveFile();
}

private void saveToolStripMenuItem_Click(object sender, EventArgs e)
{
   // Save the file.
   SaveFile();
} 
  1. Click Save All SaveAllat this point and run the program.
  2. Type a few words in the rich text box, then click save.
  3. Make sure that you remember where you saved it.
  4. Open the Windows Explorer and find the file. Windows may suggest that you open the file with Ms Word. You can also open it with WordPad.
  5. Next we will write the code to open this same file.

End of lesson, Next lesson: That is the last C# lesson in this course.