334 Part II Programming Fundamentals
- Click the Sort Text command on the File menu to sort the contents of the Abc .txt file.
The Sort Text program sorts the file in ascending order and displays the sorted list of
lines in the text box, as shown here:
- Scroll through the file to see the results of the alphabetical sort.
Notice that although the alphabetical portion of the sort ran perfectly, the sort
produced a strange result for one of the numeric entries—the line beginning with the
number 10 appears second in the list rather than tenth. What’s happening here is that
Visual Basic read the 1 and the 0 in the number 10 as two independent characters,
not as a number. Because we’re comparing the ASCII codes of these strings from left
to right, the program produces a purely alphabetical sort. If you want to sort only
numbers with this program, you need to prohibit textual input, modify the code so
that the numeric input is stored in numeric variables, and then compare the numeric
variables instead of strings.
Examining the Sort Text Program Code
OK—let’s take a closer look at the code for this program now.
Examine the Sort Text program
- On the File menu of the Sort Text program, click the Exit command to stop the
program. - Open the Code Editor for Form1, and then display the code for the
SortTextToolStripMenuItem_Click event procedure.
We’ve already discussed the first part of this event procedure, which splits each line
into an array. The remainder of the event procedure calls a procedure to sort the array,
and displays the reordered list in the text box.