320 Part II Programming Fundamentals
Examine the Text Browser program code
- On the File menu of the Text Browser form, double-click the Open command.
The OpenToolStripMenuItem_Click event procedure appears in the Code Editor.
- Resize the Code Editor to see more of the program code, if necessary.
The OpenToolStripMenuItem_Click event procedure contains the following
program code:
Dim AllText As String = ""
OpenFileDialog1.Filter = "Text files (*.txt)|*.txt"
If OpenFileDialog1.ShowDialog() = DialogResult.OK Then 'display Open dialog box
Try 'open file and trap any errors using handler
AllText = My.Computer.FileSystem.ReadAllText(OpenFileDialog1.FileName)
lblNote.Text = OpenFileDialog1.FileName 'update label
txtNote.Text = AllText 'display file
txtNote.Enabled = True 'allow text cursor
CloseToolStripMenuItem.Enabled = True 'enable Close command
OpenToolStripMenuItem.Enabled = False 'disable Open command
Catch ex As Exception
MsgBox("An error occurred." & vbCrLf & ex.Message)
End Try
End If
This event procedure performs the following actions:
o Declares variables and assigns a value to the Filter property of the open file
dialog object.
o Prompts the user for a path by using the OpenFileDialog1 object.
o Traps errors by using a Try... Catch code block.
o Reads the entire contents of the specified file by using the ReadAllText method.
o Copies the contents of the file into a string named AllText. The AllText string has
room for a very large file, but if an error occurs during the copying process, the
Catch clause displays the error.
o Displays the AllText string in the text box, and enables the scroll bars and text
cursor.
o Updates the File menu commands.
Take a moment to see how the statements in the OpenToolStripMenuItem_Click
event procedure work—especially the ReadAllText method. The error handler in the
procedure displays a message and aborts the loading process if an error occurs.
Tip For more information about the statements and methods, highlight the keyword
you’re interested in, and then press F1 to see a discussion of it in the Visual Studio Help
documentation.