I am trying to retrieve the correct value from an ArrayList of objects (.NET 1.1 Framework):
I have the following defined:
Public AlList As New ArrayList
Public Class ItemInfo
Public ItemNo As Int16
Public ItemType As String
Public Reports As Array
Public PDFs As Array
End Class
The form_load event code contains:
Dim AnItemObj As New ItemInfo
Then a loop that includes:
AnItemObj.ItemNo = AFile.RecordId
AnItemObj.ItemType = temp
AlList.Add(AnItemObj)
So I should now have an ArrayList of these objects, however if I try to retrieve the data:
MsgBox(AlList(5).ItemNo)
I always get the ItemNo of the last value in the list.
What am I missing?
Put the following code:
Dim AnItemObj As New ItemInfo
inside the loop which adds AnItemObj to the list.
When you add a reference type to a list, you are only adding the reference, not the value.
This means that if you add 10 times the same instance to a list, it will add 10 times the same reference to the list. But if afterward you still have a reference to this instance you can modify its properties and as all 10 entries in the list point to the same reference in memory, all 10 entries will be modified.
So, you've got:
Dim AnItemObj As New ItemInfo
For ...
AnItemObj.ItemNo = AFile.RecordId
AnItemObj.ItemType = temp
AlList.Add(AnItemObj)
Next
What is happening here is you're creating a single object, setting the values on it, and adding a reference to it, to your list. You're then changing your ItemInfo and addign another reference to the same item to your list
You need to construct a new object on each loop, loosely thus:
Dim AnItemObj As ItemInfo
For ...
AnItemObj = New ItemInfo
AnItemObj.ItemNo = AFile.RecordId
AnItemObj.ItemType = temp
AlList.Add(AnItemObj)
Next
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With