Visual Programming

  Visual Basic Tutorial

File Handling - Reading from Files

Objectives

This guide  will help you to: -  

  • Read information from a data file.
  • Use the EOF function.

Introduction

Creating a Data File - Review

File Input

Viewing More than One Record

       EOF

       Start Again Button

Help Desk Exercise


Introduction

You should have worked through the first file handling tutorial before attempting this one.  The first tutorial showed you how to create data files and store data into them.  This tutorial will show you how to read data from those data files.

In other words, you will learn the basics of file Input in Visual Basic


Creating a Data File - Review

In the first tutorial you created a simple form that saved information such as ID, Name and Telephone Number to a data file.

Here is a picture of that form.

The information a user types into the form is saved to a file when the user clicks on the button labeled "Save".  The code I used for saving the information is shown below. 

Note: I expect you to give your textboxes and command buttons proper names, and not leave the default names Text1, Text2 etc.

Running this program and using the form I saved the following data to my record.txt data file ready to be used for this tutorial.

The rest of this tutorial shows you how to read the information stored in this data file into a different form. If you haven't got a data file of your own, you can use my record.txt file. Don't forget to save the file into the same folder as your VB forms.


File Input

First we need to create a new form -  for reading the data from the data file.


Create a form with seven labels and one command button.

The three paler labels next to ID, Name and Telephone Number are going to display a single record from the data file when the user clicks on the 'View' command button.

Name these three paler labels lblID, lblName and lblTelNum

Now, when the user clicks the View button, we want the first record from the record.txt data file to be read and displayed in the three labels.  So we need to put the code for opening and reading the data file in the Click event for the View button.

So, make sure you are not running your program, then double-click the View button on your form.  This should take you to the form's coding window, where you should see the following...



Option Explicit

Private Sub
Command1_Click()

End Sub

Now we need to add the code to read from the record.txt data file.



Option Explicit

Private Sub
Command1_Click()
  
Dim fileName As String  ' variable for holding the file name
   Dim telNum As Long      ' variable for holding the telephone number
   Dim fullname As String   ' variable for holding the name
   Dim id As Integer           ' variable for holding the id

   fileName = App.Path & "\record.txt"   ' specify file name.

   Open fileName For Input As #1   'Open file.

   Input #1, id, fullname, telNum   'read data from file into variables.

   Close   'Close all open files 

   lblID = id    'display id in the label
   lblName = fullname   'display name in the label
   lblTelNum = telNum    'display telephone number in the label

End Sub

Try running this code.  When you click on the View button you should see the first record displayed in the labels.


Here is a picture of my form displaying the first record in my record.txt data file.

Of course, if your data file holds a different record then your form will display something different.

Remember, you can always open up your data file in notepad to check what information has been saved inside.

 


Viewing More than One Record

Have you noticed that when you run your program, it will only ever display the first record in the data file?

What if we want to view the other records?  Try adding the line (highlighted in bold) to your code and running your program.


 

 

 

 

 

 

 

 

 

 

 

 

 

Option Explicit

Private Sub
Command1_Click()
  
Dim fileName As String  ' variable for holding the file name
   Dim telNum As Long      ' variable for holding the telephone number
   Dim fullname As String       ' variable for holding the name
   Dim id As Integer           ' variable for holding the id

   fileName = App.Path & "\record.txt"   ' specify file name.

   Open fileName For Input As #1   'Open file.

   Input #1, id, fullname, telNum   'read data from file into variables.

   Input #1, id, fullname, telNum   'read data again.

   Close   'Close all open files 

   lblID = id    'display id in the label
   lblName = fullname   'display name in the label
   lblTelNum = telNum    'display telephone number in the label

End Sub
 


This time the second record from my data file is always displayed.

I expect you can guess that if I add a third line...

  Input #1, id, fullname, telNum
 

..then the third record will always be displayed

This means that while the data file is Open, the command Input reads a record (one line from the data file.)  If you use the command Input again it reads the next record in the file, then the next and so on.  However, if you ever Close the file, it will start reading from the beginning again.

So to use the Input command so that a different record is displayed every time the user clicks on the View button we need to change our code.  We need to consider the following...

  1. We need the data file to remain Open so that every time the user clicks the View button, the Input command will read a new record from the already Open file. So, we must not Open and Close the file in the Click event for the View button. 

  2. We could move the code for opening the data file to the Form_Load event.

  3. We could move the code for closing the file to the Form_Unload event.

So, lets change our code as so...


 

 

 

 

 

 

 

 

 

 

 

 

 

Option Explicit

 
  Dim fileName As String  ' variable for holding the file name
   Dim telNum As Long      ' variable for holding the telephone number
   Dim fullname As String   ' variable for holding the name
   Dim id As Integer           ' variable for holding the id

Private Sub
Command1_Click()
 

   Input #1, id, fullname, telNum   'read data from file into variables.
   lblID = id    'display id in the label
   lblName = fullname   'display name in the label
   lblTelNum = telNum    'display telephone number in the label

End Sub

Private Sub Form_Load()

  fileName = App.Path & "\record.txt"   ' specify file name.
  Open fileName For Input As #1   'Open file.

End Sub

Private Sub Form_Unload(Cancel As Integer)

   Close   'Close all open files 

End Sub

Now run your program.  Every time you click the View button, a new record should be displayed in the labels. 

However, you will notice it is easy to crash your program.  Just try clicking the View button when you are already displaying the last record in your data file.  We need to fix it so that when we are already displaying the last record, our program doesn't try to read yet another record which doesn't actually exist in the data file.

EOF

To check if the end of a file has been reached we can use the EOF function. It is important to use EOF to avoid the error generated by attempting to get Input past the end of a file.

The EOF function returns the value of False until the end of the file has been reached. Then it return True. In other words, as soon as EOF returns a value of True we know the end of the file has been reached.

Try adding the following lines (highlighted in bold) to your button click event code.


 

 

 

 

 

 

 

 

Private Sub Command1_Click()

    'check to see if end of file for file number 1 has been reached
    If (Not EOF(1)) Then 

      Input #1, id, fullname, telNum   'read data from file into variables.
      lblID = id    'display id in the label
      lblName = fullname   'display name in the label
      lblTelNum = telNum    'display telephone number in the label

   End If

End Sub

To explain the extra code...

Line: If (Not EOF(1)) Then 

This line checks to see if the end of the file has been reached for file number 1.  If it hasn't then the code inside the If block will be executed which will read from the file.  If it has reached the end of the file the code inside the If block will not be executed and no attempt will be made to read from the data file.

Line: Input #1, id, fullname, telNum

This line reads a record from the data file.  It reads each field in the record into the variables id, fullname and telNum
Every time this line is executed it reads the next record in the data file until the end of the file is reached.

Line: End If

This line is the end of the If block.

Now if the user is viewing the last record and clicks on the View button again, the program will not crash.  Nothing actually happens at all, it just keeps displaying the last record. 

One last thing, what if the user wants to view a particular record, say the second one?  The code for doing this is quite tricky.  So for now, I will show you how to let the user start viewing the records again from the beginning.

Start Again Button

Add an extra button to your form as shown in the picture below.


My 'Start Again' button is named 'Command2' by default.

When the user clicks on the 'Start Again' button, we want the data file to be closed then re-opened

Then when the Input command is used, it will start from the beginning and read the first record again.

Add the following code...

 

 

 

 

 

 

 

Private Sub Command2_Click()

Close 'Close all open files 
fileName = App.Path & "\record.txt" ' specify file name.
Open fileName For Input As #1 'Open file.

End Sub

This code closes the data file and re-opens it when the user clicks on the Start Again button.  Now when the user clicks on the View button it will start reading the records from the beginning again.


Help Desk Exercise

It is your turn to create a 'view fault log' form for your 'help desk' application.  

~Try the activity~

Activity A

Create a simple form that allows a user to view entries in a fault log.  Here is a simple example form.  You could make yours much nicer.

Note: If you have already worked through the first file handling tutorial and you have created a form that allow a user to save info to a fault log.  Then your form for viewing the fault log information should look similar to that form and not like mine below.

~Activity For the More Advanced~

Activity B

I've shown you how to let the user start viewing the records again from the beginning. It would be even better if we could allow the user view a particular record, say the second one.  The code for doing this is quite tricky.

Have a look at a some different form designs ideas for displaying particular records in data file.  Choose the method you want to use to display your fault log records.


Fini
 

 

 

   

  Unit Information

Assessment

Syllabus

Scheme of Work

Notes &Tutorials

Assignments

Quizzes

Books & Things

Links

ADR 2002