Objectives
At the end of this lab you should be able to:
- Learn how to open and close external (data) files.
- Use File Dialog boxes to locate files.
- Read data from input files and write data to output files (sequential data files)
- Understand the concept of fields and records in sequential files
- Read an entire line from a file (a record) and then breakdown into required fields.
- Use loops to read contents of data files.
- Use Try/catch blocks to handle file input/output errors.
Activity 1: An application to analyze Exam Results using files and arrays
Example: Figure below shows the contents of the file, marks.txt.
Create an Open menu item under File menu item and program the following requirements under its click event handler.
- Use a FileOpenDialog dialog box to locate and get the file path for marks.txt (you can create this file using Notepad or Notepad++ and save it in you USB drive or to any other appropriate directory)
- Once file is selected, open it and using a loop read the entire contents of the file line by line, extracting name and mark and storing them in the names and midterm marks array.
You application will still require the following array (declared at either module/class level or procedure level - you have to decide), however without the initialization and size is set at 10.
Dim strNames(9) As String
Dim dblMarks(9) As Double
The rest of the program remains the same using a command button or a menu item that when clicked produces the following statistics as before, such as:
- Average mark
- Highest mark scored and the student who scored it. (* There are no ties)
- Lowest mark scored and the student who scored it (** There are no ties)
- The range (i.e. Highest score - lowest score)
Display the results appropriate labels on your form.
Activity 2: Investment application (writing results to a file)
Modify the Investment application so that it does the following:
Have a command button or menu item called "Print to File" (that the user can click after clicking the "Calculate" button or menu item) and under its click event handler:
- Use a FileSaveDialog dialog box to choose a location to save the contents of the results in the list box.
- Once the save to directory and filename (say Investment.txt) is chosen, open it and write the contents of the textboxes [initial investment amount, the percentage return on investment over the year and the number of years of the investment (duration)] each on a separate line. Then using a loop write the entire contents of the list box with each value on a separate line.
- The format of how the file contents should appear is given below:
Investment.txt - content
Initial investment: value of textbox for initial investment
% return on investment: value of textbox for % return
Investment period: value of textbox for duration
Year 1: first item in list box
Year 2: second item in list box
Year 3: third item in list box
:
:
:
Year N: last item in list box