We have created an Application called MyNotes with a rich text box, a menu with standard items, and a toolstrip. The rich text box fills the form.
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. We will select one of these events, then write the sub to handle both events.
- Continue with the MyNotes Application.
- Add a OpenFileDialog
control to the form. It will appear under the form and be named OpenFileDialog1.
- Set the Filter property to RTF|*rtf|
- Write the code as shown below:
Private Sub OpenToolStripButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) _
Handles OpenToolStripButton.Click, OpenToolStripMenuItem.Click
OpenFileDialog1.ShowDialog()
If OpenFileDialog1.FileName <> "" Then 'They did not cancel
RichTextBox1.LoadFile(OpenFileDialog1.FileName)
Me.Text = OpenFileDialog1.FileName
End If
End Sub
- 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.
- We will modify Save as shown below:
Private Sub SaveToolStripButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) _
Handles SaveToolStripButton.Click, SaveToolStripMenuItem.Click
Dim MyFileName As String = OpenFileDialog1.FileName
If MyFileName = "" Then
SaveFileDialog1.ShowDialog()
MyFileName = SaveFileDialog1.FileName
End If
If MyFileName <> "" Then 'They did not cancel
RichTextBox1.SaveFile(MyFileName)
Me.Text = MyFileName
End If
End Sub
- Click Save All
at this point.