
07-22-2012, 08:23 PM
|
|
Newcomer
|
|
Join Date: Jul 2012
Posts: 1
|
|
Reading from text file and storing into an array
|
Hi, I am given a problem where I have a text file that contains the following:
Code:
12AVX
5
23ABC
8.97
23TWT
4.69
34ZAB
12.5
91BAN
34.67
Some of the instructions include "Define a structure named Product. The structure should contain two member variables: a String variable to store the item number and a Double variable to store the price" and "Declare a class-level array that contains five Product structure variables."
I am stuck on the following "The form’s Load event procedure should read the item numbers and prices from the ItemInfo.txt fi le and store them in the classlevel array. It also should add the item numbers to the list box."
Code:
Option Explicit On
Option Strict On
Option Infer Off
Public Class frmMain
Private ProductInfo(4) As Product
Structure Product
Public strId As String
Public dblPrice As Double
End Structure
Private Sub btnExit_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnExit.Click
Me.Close()
End Sub
Private Sub frmMain_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim inFile As IO.StreamReader
Dim intArray As Integer
Dim intLength As Integer
Dim strTemp As String
' verify that the file exists
If IO.File.Exists("ItemInfo.txt") = True Then
' open the file for input
inFile = IO.File.OpenText("ItemInfo.txt")
'process loop instructions until end of
Do Until inFile.Peek = -1
strTemp = inFile.ReadLine
Integer.TryParse(strTemp, intLength)
If intLength = 5 Then
ProductInfo(intArray).strId = strTemp
Else
Double.TryParse(strTemp, ProductInfo(intArray).dblPrice)
End If
' add the line to the list box
lstNumbers.Items.Add(ProductInfo(intArray).strId)
intArray = intArray + 1
Loop
' close the file
inFile.Close()
' select the first line in the list box
lstNumbers.SelectedIndex = 0
End If
End Sub
End Class
When I run this code my list box is empty and I am not sure where I went wrong. Any help would be appreciated.
|
|