Joe Joe - 1 month ago 8
Vb.net Question

vb.net - add object to arraylist

I'm having some trouble adding an object to an arraylist.

Basically the object has two properties (file id/name), but I can't figure out how to assign those properties. During runtime it errors out with public member on the object not found.

Private QueueList As New ArrayList
Public Sub Queue(ByVal FileName As String, ByVal FileID As Integer)
Dim QueueObj As New Object
QueueObj.FileID = "Test 1"
QueueObj.FileName = "Test 2"
QueueList.Add(QueueObj)
End Sub


I'd also like to know how I can do a loop on the arraylist and access the two properites on each record.

Thanks!

Answer

You can't just use "Object" for this. You need to build your own class:

Public Class File
    Public Property FileID As Integer
    Public Property FileName As String
    Public Sub New ()
    End Sub
    Public Sub New(ByVal FileName As String, ByVal FileID As Integer)
        Me.FileID = FileID
        Me.FileName = FileName
    End Sub
End Class

And then build your Queue like this:

Private QueueList As New ArrayList()
Public Sub Queue(ByVal FileName As String, ByVal FileID As Integer)
    QueueList.Add(New File(FileName, FileID))
End Sub
Public Sub Queue(ByVal FileObj As File)
    QueueList.Add(FileObj)
End Sub

Or, even better, use generics:

Public QueueList As New List(Of File)()
Public Sub Queue(ByVal FileName As String, ByVal FileID As Integer)
    QueueList.Add(New File(FileName, FileID))
End Sub
Public Sub Queue(ByVal FileObj As File)
    QueueList.Add(FileObj)
End Sub

Then, to loop over list:

For Each item As File In QueueList
    'Console.WriteLine(item.FileID & vbTab & item.FileName)
Next item