Visual Basic Programming

Page 17

On the previous pages, you learned how to use the list box object, and how to use sequential access files. On this page, you will learn how to read from sequential access files. Just so you know ahead of time, reading from this type of file is no big deal! I myself cannot think of a good reason to do it or use it. We could accomplish the same task using arrays, which you will learn about later in this tutorial. Sequential access files need to be read sequentially as well (down the list of records one at a time), so we cannot skip around through the file.

Now you are going to do something a bit differently.

Now we will code this application. We are going to use three form-level variables in this program; bytSelection to store the index of the selected item in the list box; strPhone to store the appropriate phone number of the name in the list box; and strName to store the entry read from the sequential access file.

We simply declared three form-level variables; two as strings and one as a byte.

This code simply sets the variable bytSelection to the ListIndex property of the list box, then looks at each entry using Select Case. It stores a number in the string variable strPhone, then displays the result in the label lblNumber.

Well at the moment, we do not have any entries in the list box, so what are we going to add to it? Simple; the names we entered into the data file in the text editor. We will add the names when the form loads.

Line 1: Open the data file Names.dat, which we created on the desktop for Input (read--get data) as file number one.
Line 2: Begin Do While loop; do statements below while the computer has not read to the end of file (EOF) number one. We need to use a loop because the computer otherwise reads only one record from the data file. It does this just because that is the way the computer reads sequential data files. The loop keeps on reading the file, therefore it keeps on getting the records.
Line 3: Read file number one (Input reads the file), and store the record in the file as strName.
Line 4: Add the record stored in strName to the list box lstNames.
Line 5: Integrate the loop; keep reading in order to get all the records.
Line 6: Close the file.

This line simply selects the first item in the list box. The application should work just fine if you wish to try it out. It does not do too much though, does it?

I hope you enjoyed this exercise with Sequential Access Files, as well as enhanced your understanding of how they work. Now we can move on to Page 18.

Top of Page

Page 1 | Page 2 | Page 3 | Page 4 | Page 5 | Page 6 | Page 7 | Page 8 | Page 9 | Page 10 | Page 11

Page 12 | Page 13 | Page 14 | Page 15 | Page 16 | Page 17 | Page 18 | Page 19 | Page 20

Page 21 | Page 22 | Page 23 | Page 24 | Page 25 | Page 26 | Page 27 | Page 28 | Page 29 | Page 30