File I/O and Array Lists Example
These instructions will build an example program that looks like this:

The new button creates an empty record. The save button will update the current record being viewed. The delete button will remove the current record being viewed. You can search for records by typing a person's name in the Search box; the results are shown dynamically while the user types in a search word.
|
|
Download the code by clicking on the Zip file. |
Instructions for Creating the Example:

The textboxes are called txtName, txtPhone, and txtSearch. The buttons are called cmdNew, cmdSave, and cmdDelete. The listbox is called lstResults.
5. At the top of your code add these two lines:
' an ArrayList is
like a vector, you can add and remove elements, and it will resize automatically
' start it out with size 10
Dim myAddressBook As New ArrayList(10)
' keeps track of the record currently being viewed
Dim currentID As Integer
6. Add an import statement to the very top of your code window to easily access File I/O classes:
' this contains the
StreamWriter and StreamReader classes
Imports System.IO
7. Create a new class named Person. Right click on your Project in the Solution Explorer and choose Add and then Add Class from the context menu. Choose the name Person.vb for your class file.

8. Our class will contain fields for a record, much like a database table. In your class, type this code:
Public Class Person
Public ID As Integer
Public Name As String
Public Phone As String
End Class
9. We'll now write three functions to handling the creation, updating, and deletion of records. The first will create new records, the second will update/save records, and the third will delete records. Later, we will use these in the events for our buttons. Place these three functions into your code:
Private Function CreateNewRecord() As
Integer
' add a new record to our ArrayList,
the function will return the ID number
' associated with the new record
' create a new object of type Person
Dim p As New Person
' return the ID number of the new record
CreateNewRecord = myAddressBook.Count + 1
' set the record ID for the new record
p.ID = myAddressBook.Count + 1
' add the record to the array list
myAddressBook.Add(p)
End Function
Private Function UpdateRecord(ByVal
currentID As Integer, ByVal Name As String, ByVal Phone As String)
' update a record with the given ID
number using the Name and Phone # parameters
' create a new object of type Person
Dim p As New Person
' find the record to update using the
ID number
For Each p In myAddressBook
If p.ID = currentID Then
Exit For
End If
Next
' update the record
p.Name = Name
p.Phone = Phone
End Function
Private Function DeleteRecord(ByVal
currentID As Integer)
' remove a record matching the
parameter CurrentID from the array list
' create a new object of type Person
Dim p As New Person
' find the record to delete
For Each p In myAddressBook
If p.ID = currentID Then
Exit For
End If
Next
' delete the record
myAddressBook.Remove(p)
End Function
10. Create two functions: one to write out records to a file from memory, and one to read records from a file into memory.
Private Function SaveRecords()
' write out the contents of the array
list to a file
' create a new object of type Person
Dim p As New Person
' open a file for output, I use false
because I don't want to append to the file
Dim sw As New StreamWriter("addressbook.txt", False)
' write out the contents of each item in the array list
For Each p In myAddressBook
sw.WriteLine(p.Name)
sw.WriteLine(p.Phone)
Next
' close the file
sw.Close()
End Function
Private Function ReadRecords()
' read in all entries from the file to
an array list
' check that our file exists
If File.Exists("addressbook.txt") Then
' open a file for
input
Dim sr As New
StreamReader("addressbook.txt")
' check if
there are more records to get
' Peek will check the next available
character but not consume it
Do Until sr.Peek = -1
' create a new empty record
currentID =
CreateNewRecord()
' put the name and phone # into the new record
UpdateRecord(currentID, sr.ReadLine, sr.ReadLine)
Loop
' close the file
sr.Close()
End If
End Function
11. Double click on your
form to create a Form1_Load event. Add this code to it so you can move the
records from your file into the program's memory. We also start the program with a new empty record.
Private Sub Form1_Load(ByVal sender
As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
' load all the records into the array
list
ReadRecords()
' create a blank record to start with
currentID = CreateNewRecord()
End Sub
12. Create a click event for the cmdNew button by double clicking on it. Add this code:
Private Sub cmdNew_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles cmdNew.Click
currentID = CreateNewRecord()
' clear the fields
txtName.Text = ""
txtPhone.Text = ""
End Sub
13. Create a click event for the cmdSave button by double clicking on it. Add this code:
Private Sub cmdSave_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles cmdSave.Click
' update the record that has the same
ID number
UpdateRecord(currentID, txtName.Text, txtPhone.Text)
' write out the records in the array
list to a file
SaveRecords()
End Sub
14. Create a click event for the cmdDelete button by double
clicking on it. We will leave a new empty record after we delete the
record. Add this code:
Private Sub cmdDelete_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles cmdDelete.Click
' delete the record matching the current ID
number
DeleteRecord(currentID)
' clear text boxes
txtName.Text = ""
txtPhone.Text = ""
txtSearch.Text = ""
' start with an empty record
currentID = CreateNewRecord()
' write out the records to a file
SaveRecords()
End Sub
15. Create a TextChanged event for the txtSearch textbox so
that when someone types their keyword, the search results will update. Add
this code:
Private Sub txtSearch_TextChanged(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles txtSearch.TextChanged
' search the array list for matching records as the user types
' create an object of type Person
Dim p As New Person
' clear the results box
lstResults.Items.Clear()
' only search if the person has typed
something in
If txtSearch.Text <> "" Then
' do a linear
search through the array list
For Each p In myAddressBook
' try a partial string match, looking at the first few
letters of each name
If Mid(p.Name,
1, Len(txtSearch.Text)) = txtSearch.Text Then
' if there's a match, stick the name in the results list
lstResults.Items.Add(p.Name)
End If
Next
End If
End Sub
16. When the user clicks on a search result, it will appear in the main
textboxes. Create a click event for the lstResults listbox.
Private Sub lstResults_Click(ByVal sender As Object, ByVal e As System.EventArgs)
Handles lstResults.Click
' show the selected item in the list
box
' create an object of type person
Dim p As New Person
' make sure something is selected in
the listbox
If lstResults.SelectedIndex <> -1 Then
' do a linear
search through the array list to find the record to display
For Each p In myAddressBook
' look for a name match
If p.Name =
lstResults.Items(lstResults.SelectedIndex) Then
Exit For
End If
Next
' load the
record
txtName.Text = p.Name
txtPhone.Text = p.Phone
' save the ID in
case we want to update
currentID = p.ID
End If
End Sub