Exercise 7 :: Text editor continued

Moving ahead

For those feeling confident, I recommend moving ahead and trying to complete this program using the example program to guide you. You should still read the exercises, but you don't need to follow the steps in the tasks. You can use the printout of the project when you get stuck. If you don't feel confident enough to attempt this, just keep reading.

Files in VB

File input and output are vital in all computing languages because a great many programs need to save and read information to long term storage. In this exercises (amongst other things) we will see how to do file IO with VB.

The basic steps for performing file IO in VB are:

The following section of code illustrates the technique.
' Open file for writing
Open "filename" For Output As #1

' Write something to this file
Write #1, "some text"
    
' Close this file
Close #1
Notice that the file is given an ID by which it is referred to after it is opened. It is important that each open file have a unique ID.

Task 1 :: Saving a file

In this task, we will add code for saving a file. This involves writing our own procedures, using the common dialog control and file IO.

  1. Add a "Save" option and a "Save As" option to your file menu. Call them mnuFileSave and mnuFileSaveAs respectively. You can do this in the same manner you added the "New" item (see Exercise 6)
  2. Go to the code editor
  3. Got to the "General/Declarations" section.
  4. Add the following code:
    Option Explicit
    
    ' Global variables
    Dim hasFileName As Boolean
    Dim currentFileName As String
    Dim isModified As Boolean
    
    This will add three global variables that keep track of whether or not the file has been saved or modified and what its name is. These are required to allow our program to decide between saving automatically with the current name or asking the user for a name. We already know what Option Explicit will do.
  5. These global variables need to be initialised. We want the initialisation to take place once when the form loads and everytime they hit the "New" option. Thus we put the initialisation code in the Form_Load() procedure which will get run when the form loads up for the first time, and in the mnuFileNew_Click() procededure .
    Private Sub Form_Load()
        ' This is the point at which we should initialise our globals
        hasFileName = False
        currentFileName = ""
        isModified = False
    End Sub
    
    Private Sub mnuFileNew_Click()
        txtDocument.Text = ""
        
        ' Set globals
        hasFileName = False
        currentFileName = ""
        isModified = False
    End Sub
    
  6. There is also another event that will effect our globals. If the user changes something in the document, we want to change the value of isModified. VB has an event that can help us, the change event. You can select the text box in the object list and then look up all the possible events in the event list. Here is the code we will need to add.
    Private Sub txtDocument_Change()
        ' When we change the text, the isModified global must
        ' change to reflect the fact that the text has now
        ' been modified
        isModified = True
    End Sub
    
  7. We must add a general purpose saving function. This can be called with one parameter for the file name. It will then take the text from the editor and save it into that file. This is the first procedure we have defined that is not connected directly to an event. To add this function, add the following code at the bottom of the code window (under all other code).
    Private Sub save(filename As String)
        ' Open file for writing
        Open filename For Output As #1
    
        ' Write the contents of the text field to this file
        Write #1, txtDocument.Text
        
        ' Close this file
        Close #1
        
        ' Set globals
        hasFileName = True
        currentFileName = filename
        isModified = False
    
    End Sub
    
    Notice that this is a private sub procedure.
  8. We are about to start programming our events. Before we can do this, we need access to the Common Dialog control. This will allow us to use common dialogs (like open and save) with very little effort. There is no button for the Common Dialog Control in our general toolbar, so we have to add one:
    • Right click in the general toolbar.
    • Choose "Components..."
    • This will bring up a list of very strange sounding controls.
    • Find the "Microsoft Common Dialog Control 6.0 (SP3)" and check it.
    • Press "OK".
    • You will now have a new button on your general toolbar, hover over it and it should say "CommonDialog".
    • Add one of these to your form. It does not matter where because it is invisible in the final program.
    Name your common dialog codDialog. Now you are ready to use the common dialogs.
  9. We now add the code for the event associated with the user hitting our "Save As" option. This will use the save function we just wrote. We write the "Save As" code before the "Save" code because it is simpler in that it will always ask the user for a file name. Add the following code to your code window:
    Private Sub mnuFileSaveAs_Click()
        ' We will need a variable for the file name
        Dim filename As String
        
        ' User will always want to choose the file name
        ' So we open the common dialog for saving
        codDialog.ShowSave
        
        ' Get the filename the user chose
        filename = codDialog.filename
        
        If filename = "" Then
            ' user did not choose a filename
            Exit Sub
        Else
            ' Call the save sub routine with this parameter
            save filename
        End If
    End Sub
    
    
  10. We now add the code for the event associated with the user hitting our "Save" option. This will use the code from the "Save As" event.
    Private Sub mnuFileSave_Click()
        ' Whether to save or not depends on the state of the globals
        ' If we have a name and are modified, we can simply save with
        ' that name
        If hasFileName Then
            If isModified Then
                save currentFileName
            Else
                Exit Sub
            End If
        Else
            If isModified Then
                ' This file has no name so we need to work as if the
                ' user had pressed "save as"
                mnuFileSaveAs_Click
            Else
                MsgBox "Nothing to save yet"
                Exit Sub
            End If
        End If
            
    End Sub
    
    Notice we have used a number of concepts from previous exercises, including if statements and message boxes.

Error handling

Dealing with possible errors is an important part of all programming, but it becomes particularly important when dealing with files. The user may specify a file that does not exist, is unable to be written (read only) or that is the wrong format. These are things that we, as programmers, cannot control. However, we must be prepared to program for such situations. VB provides an error handing mechanism built around the GoTo statement. A GoTo statement tells the program to jump to another part of the code. The place you want to jump to needs to be marked with a place marker.

The basic steps in error handling in VB are: The following example may shed a little extra light on the situation.
    ' Set up error handlers
    On Error GoTo error_marker

		' In here will go some code that may create an error
		' ...
		' ...    
    
    ' this section of code will end this sub routine
exit_marker:
    Close #2
    Exit Sub
    
error_marker:
    Select Case Err.Number
        Case 53     ' File not found error has occurred
            MsgBox "That file does not exist"
        Case Else
            MsgBox "There was an error"
            Err.Raise Err
    End Select
    GoTo exit_marker
    
    ' After the error handling, the function will simply end
End Sub
The On Error line specifies where to jump to when an error occurs. Each specific error is given a number. You use the Select statement like a special type of if. The general form of a Select statement is:
Select Case "condition"
  Case "one posibility"
	  "code"
  Case "another possibility"
	  "code"
  Case "another possibility"
	  "code"
  Case Else
	  "code for if none of the possibilies are true"
End Select
You write code in the select statement to handle all the errors you expect to get. In the else section, write a general error handler to deal with all the other cases.

Task 2 :: Opening a file and error handling

In this task, we will add code for opening a file, in the process, we will have to do our first bit of error handling.

  1. Add an "Open" item to the file menu. Name it mnuFileOpen.
  2. Go to the code window and open the procedure for the click event of this menu item.
  3. Add the following code:
        ' We will need a variable for the file name
        Dim filename As String
        Dim fileContents As String
        
        ' User will always want to choose the file name
        ' So we open the common dialog for opening files
        codDialog.ShowOpen
        
        ' Get the filename the user chose
        filename = codDialog.filename
        
        ' Set up error handlers
        On Error GoTo open_errors
        
        ' Ends procedure if user pressed cancel or did not enter filename
        If filename = "" Then
          GoTo open_exit
        End If
        
        ' Open the file with the chosen name
        Open filename For Input As #2      ' This file can be read but not written
        
        ' Read the contents of the text field to this file
        Input #2, fileContents
        txtDocument.Text = fileContents
        
        ' Set globals
        isModified = False
        currentFileName = filename
        hasFileName = True
        
        ' this section of code will end this sub routine
    open_exit:
        Close #2
        Exit Sub
        
    open_errors:
        Select Case Err.Number
            Case 53     ' File not found error has occurred
                MsgBox "That file does not exist"
            Case Else
                MsgBox "There was an error"
                Err.Raise Err
        End Select
        GoTo open_exit
    
  4. Now save and run your program. Save some files, open some files. I have included some example files that have been saved in the "docs" directory. They are saved with .mpd file extension (mpd stands for MacPaD).

NEXT ->


Matthew Roberts, Macquarie University 2002