In my VB 6 code, I had many classes and depended on the ability to loop through the objects to get at the data. How is this done in VB.NET? Here's a very simple example of what I'd like to be able to do in VB.NET. In my Accounts class I wrote my own Count property, but the Item property is the main problem. There must me a new way of doing this.

Dim x as Integer
Dim obj as Account
Dim col as Accounts

For x = 1 to col.Count
Set obj = col.Item(x)
Msgbox(obj.Name)
Next

Thanks in advance,
Sheryl

Yes, there is a way. First, here's a sample Account and Accounts (without any error handling):

Option Explicit On
Option Strict On
Public Class Account

  Private _Name As String

  Public Property Name() As String
    Get
      Return _Name
    End Get
    Set(ByVal value As String)
      _Name = value
    End Set
  End Property

  ' More properties

End Class

Public Class Accounts

  Private m_coll As List(Of Account)

  Public Sub New()
    '
    ' Initialize class
    m_coll = New List(Of Account)

  End Sub

  Protected Overrides Sub Finalize()
    '
    ' Terminate
    '
    MyBase.Finalize()

  End Sub

  ' LOTS of more code to save, load, add , remove etc. items

  Public Function Item(ByVal Index As Integer) As Account
    '
    ' Return a record from the collection
    Return CType(m_coll.Item(Index), Account)

  End Function

  Public Function Count() As Integer
    '
    ' Return the number of records in the collection
    Return m_coll.Count

  End Function

End Class

and now you can loop the collection:

Dim x As Integer
Dim obj As Account
Dim col As Accounts

col = New Accounts
' Fill col with data

For x = 0 To col.Count - 1
  obj = col.Item(x)
  MessageBox.Show(obj.Name, "Collection Item", MessageBoxButtons.OK, MessageBoxIcon.Information)
Next x

Notice that all collections and arrays start in .NET from index = 0, not from 1 like in VB6. This sample used a List( Of <type>), there's a few more collection types you can use.

When you get really into .NET collections, search examples how to use IEnumerable and IEnumerator interfaces. Then you can use

For Each obj In col
  MessageBox.Show(obj.Name, "Collection Item", MessageBoxButtons.OK, MessageBoxIcon.Information)
Next

syntax in your code.

Thank you so much! This is going to help me a lot. ~ Sheryl

Why not just use

For Each <variable> as <type of every item> in <collection>

It might be a lot easier to iterate through a collection of items.

Because then the class would have to implement IEnumerable and IEnumerator interfaces.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.