On this page, you will learn about a different way to input data and store it, along with the list box object. You will learn this using sequential access files. A sequential access file is a data file (.dat) that stores records which are entered by the user. For instance, a user could enter a name into a program, and the program may take that name and write it to a data file. The user may also retrieve certain part of the file as well. Sequential access files are named as so because each record is written to the data file one after another. Now we can begin.
You will first learn about the list box object.
Open a new project and name it Lists or what ever you like.
Name the form frmLists.
Set the form's Height property to 4830 and its Width property to 4500.
Set the form's BorderStyle property to 1-Fixed Single and its MinButton property to False.
Set the form's StartUpPostion property to 2-Center Screen.
I know that we had previously done the same task with code, but I just wanted to make you aware that you may also do this without coding.
Set up the interface below:
The top object is a text box as I am sure you guessed, and the two objects beneath it are list boxes.
Name the text box txtAdd.
Name the top list box lstStuff.
Name the list box below lstNew.
Set the Sorted property of lstStuff and lstNew to True. This sorts the entries in a list box alphabetically.
Name the command buttons cmdAdd, cmdRemove, cmdClear. We are not using an exit button for the sake of a more attractive interface.
Lock the controls on the form.
Before we continue, we need to understand some of the methods and properties for list boxes. The ones we will use are listed below.
Keyword |
Type | Purpose | Syntax |
AddItem | Method | Adds string (text) to list | lstName.AddItem String **A string is just text** |
RemoveItem | Method | Removes string from list | lstName.RemoveItem String |
List | Property | Used as index; stores entire list | lstName.List(Value of items' index(es)) |
ListIndex | Property | Used to look at a particular list entry | lstName.ListIndex = Value Value is a numeric value. Starts at 0. Setting ListIndex to 0 selects the first list entry, 1 the second etc... |
Text | Property | Used to take the text from the selected entry | frmName.Caption = lstName.Text |
Clear | Method | Clears the list box | lstName.Clear |
Open the code window for the cmdAdd command button.
Press tab, then type the following line:
lstStuff.AddItem txtAdd.Text
The line you entered uses the method AddItem to put the text from txtAdd into the list box lstStuff. It simply adds the item that you designate (in this case the text in txtAdd), just as the code reads.
Now let's code the cmdRemove command button.
In the code window for the object cmdRemove, press tab, then type the following line:
lstNew.RemoveItem lstNew.ListIndex
The line you entered uses the RemoveItem method to delete the selected item (lstNew.ListIndex) from the list box lstNew.
Open the code window for the text box txtAdd
Press tab, then type the following lines:
If Len(txtAdd.Text) > 0 Then 'Done
cmdAdd.Enabled = True 'Done
Else: cmdAdd.Enabled = False 'Done
End If 'Done
Line 1: This is a new function. This tests to see if the length
(Len) of the string (String: The text in something)
txtAdd.Text is greater than 0. One character is a length of 1.
Line 2: If the length is greater than zero, it will enable the cmdAdd
command button.
Line 3: Otherwise (the length of txtAdd.Text is zero), set
the Enabled property of cmdAdd to False (Disable
it).
Line 4: End the If statement.
If you run the application, you can add the text from the text box into the first list box. You may also remove items from the list box below by pressing the Remove button. You may have noticed that you get an error if you try to remove an item from the list box without an item selected. We will fix this problem shortly.
Open the code for the cmdRemove object and type the following lines below the existing code:
txtAdd.SetFocus
If Len(lstNew.Text) > 0 Then cmdRemove.Enabled = True Else cmdRemove.Enabled = False
Line 1: Sets the focus to the txtAdd object; makes
txtAdd the active object.
Line 2: Tests the length of the item selected in the list box lstNew.
When (If) the length of the text is greater than 0, the command
button cmdRemove is enabled. Otherwise (Else), cmdRemove is
disabled.
If you try to remove text in a list box when nothing is selected, Visual Basic creates an error.
Open the code window for the cmdClear object
Type the following lines:
lstNew.Clear 'Clears lstNew
lstStuff.Clear 'Clears lstStuff
Open the code window for the lstStuff Double Click event procedure. Select the event using the event box in the code window.
Type the following lines:
lstNew.AddItem lstStuff.Text 'Adds the selected entry in
lstStuff to the lstNew list box
lstNew.ListIndex = 0 'Selects the first entry in lstNew
Open the code window for the list box lstNew using the Click event (Remember to look at the event box to confirm).
Enter the following lines:
frmList.Caption = lstNew.Text
If Len(lstNew.Text) > 0 Then cmdRemove.Enabled = True Else cmdRemove.Enabled = False
Line 1: Sets the forms caption to the text of the
selected item in the lstNew list box
Line 2: Tests to see if the length (Len) of the string
(or text) in the lstNew
list box is not zero (greater than zero). If the length is greater, cmdRemove
is enabled. Otherwise, cmdRemove is disabled. A length of 1
is one character, 2 is two characters, and so forth
If we do not test the length of the text in the list box, the code makes the program add nothing, which generates an error.
Personally, I think we have a very nice program using list boxes; but how about coding some more stuff to test the list in each list box. We could display a message if the user tries to enter text into the list box that already exists. We do this by using the For Next loop. Let's start the process.
Go into the General Declarations section of the code window using the object box.
Type Dim intCheck As Integer, which declares a form-level variable intCheck as an Integer.
Open the code for the cmdAdd object.
Press enter ahead of the line lstStuff.AddItem txtAdd.Text to create a line above it, then type the following lines below:
For intCheck = 0 To lstStuff.ListCount
If lstStuff.List(intCheck) = txtAdd.Text Then
MsgBox "Item already exists."
Exit Sub
End If
Next intCheck
To understand the line above, see below:
Line 1: Begins For Next loop, starting intCheck
at zero and stops at the value of the amount of entries (list count) in
the list box lstStuff.
Line 2: Tests to see if somewhere in the list (the List
property includes the entire list) of lstStuff the same text as the text
in the text box txtAdd exists. The variable intCheck in the
parenthesis designates the entry of the list, which changes as the loop loops,
or increments.
Line 3: If somewhere in the list the text is the same as the text in txtAdd,
display a message box (MsgBox) reading Item already exists.
Line 4: Exits the sub-procedure. The code will otherwise add the text in txtAdd
regardless because of the lstStuff.AddItem txtAdd.Text line beneath
the loop.
Line 5 ends the If statement, and Line 6 increments the For
Next loop; goes to the next value of intCheck.
Now for the last list box, open the dblClick event procedure for the lstStuff object.
The code for this object is IDENTICAL to the code for the cmdAdd command button, with the exception of different object names. We want to add the selected entry of the lstStuff object to the lstNew object. Try it alone if you want a challenge. Enter the code necessary below the existing code in the lstStuff dblClick procedure. Having difficulty? See below:
For intCheck = 0 To lstNew.ListCount
If lstNew.List(intCheck) = lstStuff.Text Then
MsgBox "Item already exists."
Exit Sub
End If
Next intCheck
Good for you if you did it without looking! We are done with list boxes. Now that we have learned about the list box, we may continue, and learn about Sequential Access Files. Save the form and project only if YOU want to. Let us continue.
Set up the interface below:
Set the form's Width property to 6180 and its Height property to 4530.
Set the form's BorderStyle property to 1-Fixed Single and its MinButton property to True.
Start with the frame object; set its Height property to 2775 and its Width property to 4140.
Place the objects as best as you can to correspond with the image above.
Name the command buttons as follows top to bottom. Notice the access keys.
cmdAdd
cmdPrint
cmdClear
cmdExit
Set the cmdAdd command button's Default property to True.
Name the list box lstFruits, and the label above it lblList. Be sure to set the access key to F as seen above.
Name all the labels above the squares as lblFruitName. Set the index property of each label appropriately, incrementing left to right.
Ex: lblFruitName(0) is the label reading Apples:;
lblFruitName(1) is the label reading Bananas: etc.
Place one square label on the form.
Name the square label lblFruit. Set the index property of the label to 0.
Set the label's Height property to 495 and its Width property to 615.
With the label selected, press Ctrl then C to copy the control.
Press Ctrl then V eleven times to paste more labels on the form.
Cut and paste the labels to add them to the frame object.
Do your best to set up the form as it appears above.
Name the label displaying "Total fruits:" as lblTotal.
Set the TabIndex property for the objects as follows:
lblList: 0
lstFruits: 1
cmdAdd: 2
cmdPrint: 3
cmdClear: 4
cmdExit: 5
Lock the controls on the form.
Name the form frmFruits.
Congratulations if you survived the tedious process setting up the interface. Now we will begin the coding!
Open the code window for the form's Load procedure, press tab, then type lstFruits.ListIndex = 0.
This line simply selects the first item in the list box lstFruits.
We are going to use seven variables for this application, so let's declare them now.
In the General Declarations section of the code
window, type the following lines:
Dim bytResponse As Byte
Dim strEntries(11) As String, intFruits As Integer
Dim lngWrite As Long, lngEntries As Long, lngTotal As Long
You may wonder what the parenthesis are next to the variable strEntries are. This sets up dimensions for the variable, or different parts to store data in. This is called an array. Arrays are usually used to store a large amount of related data. Because we are going to store a numerous amount of related text in a variable, it is better sometimes to just use one variable with more than one dimension.
In the code window for the cmdAdd object, press tab, then type the following line:
lngEntries = Val(InputBox("Enter amount of " & LCase(lstFruits.Text) & ":", "Add Fruits"))
The line above stores the value of the text entered into the input box. The LCase used is a function used to change the text of the selected item in the list box lstFruits to lower case letters. It looks much better in the input box this way.
Below the line you entered, type the following code:
If Str(lngEntries) = "" Then lngEntries = 0
This line of code tests to see if there is anything in the variable lngEntries. The Str prefix in front of the variable treats it as a string. The Long data type stores numeric values and not text. The variable is however accepting text, so it behave like a string. If it is not treated as a string, we cannot test to see if the text in the InputBox is blank ("") because the input box accepts strings. If the user enters nothing, the variable lngEntries stores 0.
Below the line you just entered, type the following code:
Open "C:\Windows\Desktop\fruits.dat" For Append As #1
The line above opens the file fruits.dat in order to append (add to) to the file as file #1
Below the line you just entered, type the following code:
For lngWrite = 1 To Val(lngEntries)
Write #1, lstFruits.Text, lstFruits.ListIndex
Next lngWrite
Line 1: Begin For Next loop; starts lngWrite
at 1 and goes up to whatever the user enters into the InputBox, which was stored
in lngEntries.
Line 2: Writes the text of the list box lstFruits (the selected
item in the list box) then the index of the list item in lstFruits to file
number 1, which is what the file was opened as above earlier
Line 3: Goes to the next value of lngWrite. Remember that lngWrite
only goes up to the value of lngEntries, which is what YOU enter.
Below the lines you just entered, type the following code:
bytFruit = lstFruits.ListIndex
lblFruit(bytFruit).Caption = lngEntries + Val(lblFruit(bytFruit).Caption)
Close #1
Line 1: Sets the variable bytFruit to the selected
item in the list box lstFruits.
Line 2: Sets the caption of the label with the index corresponding with
the selected list item to lngEntries (what the user enters in the Input
Box), then adds the current value of the label to the variable's (lngEntries) value.
Line 3: Closes the file. If you want to open the same file for a
different access method, such as Output, it must be closed first.
Now let's get this thing to add up the quantities.
Below the last line you entered, type the following code:
For intFruits = 0 To 11
lngTotal = Val(lblFruit(intFruits).Caption) + lngTotal
Next intFruits
lblTotal.Caption = "Total fruits: " & lngTotal
Line 1: Begins For Next loop; sets the
range of values of intFruits of 0 to 11, the index range of
the label lblFruit.
Line 2: Takes the value of the caption in the label lblFruit with
index of wherever the loop is (0 through 11) and adds the value to
lngTotal, then sets the total value equal to itself (lngTotal).
Line 3: Increments the loop; goes to the next value of intFruits.
Line 4: Sets the caption of lblTotal to Total fruits: then lngTotal.
If you run the application, you may notice that when you try to add fruits, the first entry works fine, but then it keeps incrementing by the value of the label corresponding with the selected item in the list box. This is because the number in the label's caption is set to add to lngTotal. To solve this, all we need to do is reset lngTotal.
In a new line above the loop we created, type: lngTotal = 0 'Reset lngTotal to be recalculated
Now we will code the cmdExit button, but a little differently.
In the General Declarations section of the code window, declare the variable bytResponse, the same way we declare all variables.
Dim bytResponse as Byte
In the code window for the cmdExit button, type the following lines:
bytResponse = MsgBox("Are you sure you want to exit?", vbYesNo + vbQuestion,
"")
If bytResponse = vbYes Then End
Line 1: Displays a message box including a yes and no
button(vbYesNo), and displays it as a question (vbQuestion)
Line 2: Tests bytResponse; if the user clicks Yes, end the
application.
Now for the clear button.
In the code window for the cmdClear button, type the following line:
bytResponse = MsgBox("Are you sure you want to clear all records?", vbYesNo + vbQuestion, "")
This does the same as above, but with a different message
Below the line you just entered, type the following lines:
If bytResponse = vbYes Then
Open "C:\Windows\Desktop\fruits.dat" For Output As #1
Write #1,
Line 1: Tests to see whether the user pressed Yes
Line 2: When the users presses Yes, open the file C:\Windows\Desktop\fruits.dat
to write data to it (Output), which writes over existing data.
Line 3: Write nothing to file number 1, thus clearing it.
Now that we have cleared the records in the file, let's clear the form.
Below the lines you just entered, type the following lines:
For bytFruit = 0 To 11
lblFruit(bytFruit).Caption = ""
Next bytFruit
cmdAdd.SetFocus
End If
Close #1
lblTotal.Caption = "Total fruits:"
Line 1: Looks at bytFruit 0 to 11
Line 2: Clears the caption of lblFruit with index of 0 to 11
(all of them).
Line 3: Increments loop; goes to next value of bytFruit.
Line 4: Sets the focus to the command button cmdAdd (makes it
active).
Line 5: Ends the If statement.
Line 6: Closes the file.
Line 7: Sets the caption of the label lblTotal to Total fruits.
I hope that you enjoyed this long tutorial. Now you may move on to Page 17.