Displaying Text Files by Using a Text Box Object
The simplest way to display a text file in a program is to use a text box object. As you have learned, you can create text box objects in any size. If the contents of the text file don't fit neatly in the text box, you can also add scroll bars to the text box so that the user can examine the entire file. To use the Visual Basic language to load the contents of a text file into a text box, you need to use four functions. These functions are described in the following table and are demonstrated in the first exercise in this chapter. As I noted earlier, several of these functions replace older keywords in the Visual Basic language.
Function | Description |
FileOpen | Opens a text file for input or output |
LineInput | Reads a line of input from the text file |
EOF | Checks for the end of the text file |
FileClose | Closes the text file |
Opening a Text File for Input
A text file consists of one or more lines of numbers, words, or characters. Text files are distinct from document files and Web pages, which contain formatting codes, and from executable files, which contain instructions for the operating system. Typical text files on your system are identified by Microsoft Windows Explorer as “Text Documents” or have the file name extension .txt, .ini, .log, or .inf. Because text files contain only ordinary, recognizable characters, you can display them easily by using text box objects.
By using an OpenFileDialog control to prompt the user for the file's path, you can let the user choose which text file to open in a program. This control contains the Filter property, which controls the type of files displayed; the ShowDialog method, which displays the Open dialog box; and the FileName property, which returns the path specified by the user. The OpenFile Dialog control doesn't open the file; it just gets the path.
The FileOpen Function
After you get the path from the user, you open the file in the program by using the FileOpen function. The abbreviated syntax for the FileOpen function is
FileOpen(filenumber, pathname, mode)
You can find the complete list of arguments in the Visual Basic online Help. These are the most important:
filenumber is an integer from 1 through 255.
pathname is a valid Microsoft Windows path.
mode is a keyword indicating how the file will be used. (You'll use the OpenMode.Input and OpenMode.Output modes in this chapter.)
The file number is associated with the file when it's opened. You then use this file number in your code whenever you need to refer to the open file. Aside from this association, there's nothing special about file numbers; Visual Basic simply uses them to keep track of the different files you open in your program.
A typical FileOpen function using an OpenFileDialog object looks like this:
FileOpen(1, OpenFileDialog1.FileName, OpenMode.Input)
Here the OpenFileDialog1.FileName property represents the path, OpenMode.Input is the mode, and 1 is the file number.
TIP
Text files that are opened by using this syntax are called sequential files because you must work with their contents in sequential order. In contrast, you can access the information in a database file in any order. (You'll learn more about databases in Chapter 18, “Getting Started with ADO.NET.”)
The following exercise demonstrates how you can use an OpenFileDialog control and the FileOpen function to open a text file. The exercise also demonstrates how you can use the Line-Input and EOF functions to display the contents of a text file in a text box and how you can use the FileClose function to close a file. (For more information about using controls on the Dialogs tab of the Toolbox to create standard dialog boxes, see Chapter 4, “Working with Menus, Toolbars, and Dialog Boxes.”)
Run the Text Browser program
Start Microsoft Visual Studio, and open the Text Browser project in the c:\vb05sbs\chap13\text browser folder.
The project opens in the IDE.
If the project's form isn't visible, display it now.
The Text Browser form appears, as shown here:
The form contains a large text box object that has scroll bars. It also contains a menu strip object that places Open, Close, and Exit commands on the File menu; an open file dialog object; and a label providing operating instructions. I also created the property settings shown in the following table. (Note especially the text box settings.)
Object | Property | Setting |
txtNote | Enabled Multiline Name ScrollBars | False True txtNote Both |
CloseToolStripMenuItem | Enabled | False |
lblNote | Text Name | “Load a text file with the Open command.” lblNote |
Form1 | Text | “Text Browser” |
Click the Start Debugging button on the Standard toolbar.
The Text Browser program runs.
On the Text Browser File menu, click the Open command.
The Open dialog box appears.
Open the c:\vb05sbs\chap13\text browser folder.
The contents of the Text Browser folder are shown here:
Double-click the Badbills.txt file name.
Badbills, a text file containing an article written in 1951 in the United States about the dangers of counterfeit money, appears in the text box, as shown here:
Use the scroll bars to view the entire document. Memorize number 5.
When you're finished, click the Close command on the File menu to close the file, and then click the Exit command to quit the program.
The program stops, and the IDE returns.
Now you'll take a look at two important event procedures in the program.
Examine the Text Browser program code
On the Text Browser form File menu, 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 = "", LineOfText As String = "" OpenFileDialog1.Filter = "Text files (*.TXT)|*.TXT" OpenFileDialog1.ShowDialog() 'display Open dialog box If OpenFileDialog1.FileName <> "" Then Try 'open file and trap any errors using handler FileOpen(1, OpenFileDialog1.FileName, OpenMode.Input) Do Until EOF(1) 'read lines from file LineOfText = LineInput(1) 'add each line to the AllText variable AllText = AllText & LineOfText & vbCrLf Loop 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 MsgBox("Error opening file.") Finally FileClose(1) 'close file End Try End If
This event procedure performs the following actions:
Declares variables and assigns a value to the Filter property of the open file dialog object.
Prompts the user for a path by using the OpenFileDialog1 object.
Traps errors by using a Try…Catch code block.
Opens the specified file for input by using the FileOpen function.
Uses the LineInput function to copy one line at a time from the file into a string named AllText.
Copies lines until the end of the file (EOF) is reached or until there's no more room in the string. 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.
Displays the AllText string in the text box, and enables the scroll bars and text cursor.
Updates the File menu commands, and closes the file by using the FileClose function.
Take a moment to see how the statements in the OpenToolStripMenuItem_Click event procedure work—especially the FileOpen, LineInput, EOF, and FileClose functions. 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 functions, highlight the keyword you're interested in, and press F1 to see a discussion of it in the Visual Basic online Help.
Display the CloseToolStripMenuItem_Click event procedure, which is executed when the Close menu command is clicked.
The event procedure looks like this:
txtNote.Text = "" 'clear text box lblNote.Text = "Load a text file with the Open command." CloseToolStripMenuItem.Enabled = False 'disable Close command OpenToolStripMenuItem.Enabled = True 'enable Open command
The procedure clears the text box, updates the lblNote label, disables the Close command, and enables the Open command.
Now you can use this simple program as a template for more advanced programs that process text files. In the next section, you'll learn how to type your own text into a text box and how to save the text in the text box to a file on disk.