Reputation: 31
I have a class that reads from a text file, and adds it to a collection. I'm trying to figure out how to read from the collection to populate a combobox upon loading of the program.
BillingData Class
Public ReadOnly Property Clients As Collection
Get
Return mClients
End Get
End Property
Sub New()
mClientFile = OpenText("clients.txt")
Dim mClients As New Collection
While Not mClientFile.EndOfStream
mClients.Add(mClientFile.ReadLine())
End While
mClientFile.Close()
mainForm
Private Sub frmMain_Load(sender As Object, e As EventArgs) Handles MyBase.Load
client = New BillingData()
Dim i As Integer
While i < client.Clients.Count
cbClient.Items.AddRange(client.Clients(i))
i = i + 1
End While
End Sub
Upvotes: 1
Views: 6390
Reputation: 1536
I made 3 changes to the frmMain_Load
subroutine.
i
to 1.<=
.Used Add
instead of AddRange
.
Private Sub frmMain_Load(sender As Object, e As EventArgs) Handles MyBase.Load
client = New BillingData()
Dim i As Integer = 1
While i <= client.Clients.Count
cbClient.Items.Add(client.Clients(i))
i = i + 1
End While
End Sub
An interesting thing to note for the first change (initializing i to 1): The value of Clients at index 0 is "empty placeholder for a 1-based array". This basically means the collection starts at index 1. The code will sort of throw a phantom exception that never gets caught - this is typical in VB.net form load routines. You can test this out by setting a breakpoint in your load code and see that it never gets to the line i = i + 1
. If you placed your code in a button click event instead, you would see the code break on the exception. Moral of the story is to be careful on any code that you put on form load routines, because you do not always get immediate feedback if there is a bug in the code.
Upvotes: 2
Reputation: 54532
You can try adding your Collection to the ComboBox's DataSource. If your problem is that your Collection is not initialized before you add it to the ComboBox you can add an event to your BillingData Class that is raised when the data is ready. You could then add the collection to your ComboBox in the Event Handler.
cbClient.DataSource = client.Clients
Upvotes: 1