Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations biv343 on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Arraylist issue in vb.net 2008

Status
Not open for further replies.

jake007

Programmer
Jun 19, 2003
166
US
I am trying to populate an array list from a fixed length file. The code processes through the file ok, but my arraylist ends up with 17 copies (the number of records in the file) of the last record? Her is the code

Public Sub LoadMachineArray()
Dim NewMachine As New Machine
Dim sr As StreamReader
Dim LineData As String

MachineList.Clear()

sr = New StreamReader("c:\SupplyData\Machines.txt")

LineData = sr.ReadLine
Do While (Not LineData Is Nothing)

NewMachine.MachineId = Mid(LineData, 1, 19).Trim
NewMachine.Type = Mid(LineData, 20, 19).Trim
NewMachine.Supply(0) = Mid(LineData, 40, 19).Trim
NewMachine.Supply(1) = Mid(LineData, 60, 19).Trim
NewMachine.Supply(2) = Mid(LineData, 80, 19).Trim
NewMachine.Supply(3) = Mid(LineData, 100, 19).Trim
NewMachine.Supply(4) = Mid(LineData, 120, 19).Trim
NewMachine.Supply(5) = Mid(LineData, 140, 19).Trim
NewMachine.Supply(6) = Mid(LineData, 160, 19).Trim
NewMachine.Supply(7) = Mid(LineData, 180, 19).Trim
NewMachine.Supply(8) = Mid(LineData, 200, 19).Trim
NewMachine.Supply(9) = Mid(LineData, 220, 19).Trim
NewMachine.Supply(10) = Mid(LineData, 240, 29).Trim

MachineList.Add(NewMachine)
LineData = sr.ReadLine
Loop
'NewMachine = Nothing

For Each mach As Machine In MachineList
ListBox1.Items.Add(mach.MachineId & "-" & mach.Type & "-" & mach.Supply(0))
Next
End Sub


The list box (listbox1) ends up with 17 copies of the last record?

 

This is happening because you are using the same Machine object (NewMachine) for each line. So you store the first Machine with its data, then change all of the values in the Machine object when you read the second line, and so forth. The fix is easy, just create a new Machine object for each iteration of the loop:

Do While (Not LineData Is Nothing)

[red]NewMachine = New Machine[/red]

'other code

Loop


I used to rock and roll every night and party every day. Then it was every other day. Now I'm lucky if I can find 30 minutes a week in which to get funky. - Homer Simpson

Arrrr, mateys! Ye needs ta be preparin' yerselves fer Talk Like a Pirate Day!
 
Thanks jebenson. Can't believe i missed that. Looked at the code for too long I guess.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top