Filling a listbox with collection items

P

Petter L

I have set up a test program on how to use colletions saved and loaded from
a file. It was a part of a other program until this happends.
The saving process working fine but it looks like something goes wrong in
the read and refill the listbox. Say there is three items listed in the
file. It semes that the reading process works but I only get the last item
three times insted of three different one.

This is the reading code that was put in a module


Public Excludelist As New ExListCollection

Public Fexclude As New ExFile

Dim path As String = "c:\MyTest.txt"

Dim fs As FileStream



Public Sub ReadExclude()



Try

Dim sr As StreamReader = File.OpenText(path)

Dim inp As String

Do While sr.Peek() >= 0

Fexclude.ExFilename = sr.ReadLine

Excludelist.Add(Fexclude)

MessageBox.Show(Fexclude.ExFilename)

Loop

sr.Close()

Catch e As Exception

MessageBox.Show("The process failed: {0}", e.ToString())

End Try

End Sub



And this was put in the forms form_Load


Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles MyBase.Load



Dim count As Integer

ReadExclude()

For count = 0 To Excludelist.Count - 1

MessageBox.Show("List " & Excludelist.Item(count).ExFilename)

lstExclude.Items.Add(Excludelist.Item(count).ExFilename)

Next

End Sub



It looks like the collection as got the data from the file right but when it
is presented again it get wrong.
Have someone any clue what is wrong her ?


PetterL
 
G

Guest

Petter,

Each time through your loop you need to create a new instance of the
Fexclude object:

Do While sr.Peek() >= 0

Fexclude = New ExFile '<--------------- create a new instance

Fexclude.ExFilename = sr.ReadLine

Excludelist.Add(Fexclude)

MessageBox.Show(Fexclude.ExFilename)

Loop
 
C

Cor Ligthert

Petter,

Why not split up the problem yourself first.

First try it with an arraylist to get one field from a record
Than build your own class to hold the data which you add as an object to the
arraylist
Than make your own collection to make it complete.

You have now taken to much problems in one time, from which I get the idea
that you don't know exactly how to handle them.

In addition, be aware that the Listbox has self a fine itemArray which you
can fill with objects (and set than the displaymember to the property you
want to display).

Just my thought,

Cor
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top