This example will read in a CSV (comma separated values) with the name and year born of a person. As the file is read in the name of the person will be added to a combo box and the year born will be added to an array.
When the user selects a name from the combo box, it will display the year born.
The file: Copy the list of names and years and save it as C:/myData/names.txt. If you save it to a different location, be sure to change the code to your location
Amy,2010
Bill,1985
Debbie,1976
Ian,1987
Jay,1974
Josh,2003
Lin,2009
Mark,1979
Paul,2001
The "Lookup" Program
This program reads the file shown above. Each line in the file is added to the ComboBox
and displayed.
- Start a new Windows application, name it LookupFile.
- Add a ComboBox
to the form. Name it CboNames.
- Add a label
named lblInfo.
- Add the following code to form load:
Public Class Form1
Dim Years(1) As Integer
Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
Dim S As String = ""
Dim Count As Integer = 0
FileOpen(1, "C:\myData\names.txt", OpenMode.Input) 'open the file for input
While Not EOF(1) 'EOF=End of file, this loops to read all recordds
S = LineInput(1) 'read from file 1
Dim words As String() = S.Split(",")
Me.CboNames.Items.Add(words(0)) 'add the name read to the combo box
ReDim Preserve Years(Count) 'make the array Years big enough to hold the new year
Years(Count) = words(1) 'the year born
Count = Count + 1
End While
FileClose(1) 'close file 1
If Me.CboNames.Items.Count > 0 Then 'make sure the file was read
Me.CboNames.SelectedIndex = 0 'display 1st item in list
End If
End Sub
Private Sub CboNames_SelectedIndexChanged(sender As System.Object, e As System.EventArgs) Handles CboNames.SelectedIndexChanged
Dim num As Integer = CboNames.SelectedIndex
Dim ThisYear As Integer = DateTime.Today.Year
Dim Age As Integer = ThisYear - Years(num)
Me.LblInfo.Text = CboNames.SelectedItem & " will be " & Age & " in " & ThisYear
End Sub
End Class
Experiment:
Add more names to the list.
Use the example to create acompletely different lookup program.