messed up listbox entries

  • Thread starter Patrick Sullivan
  • Start date
P

Patrick Sullivan

I am trying to read a text file laid out like, "textfield1, textfield2,
etc," and only extract the first value (textfield1) to add to the listbox.
But instead of listing vertically, I get three rows across of textfield1,
which is the correct data, but not the correct format. I put a crlf in the
lines, but that did not help at all. TIA

Private Sub LoadListbox()

Try

Dim sr As StreamReader = New StreamReader("Names.txt")

Dim line As String

line = sr.ReadLine()

Do Until sr.Peek = -1

line = sr.ReadLine()

'MsgBox("Line is " & line.Length & " long")

lstNames.Items.Add(line.Substring(0, (line.IndexOf(","))) & vbCrLf)

Loop

sr.Close()

Catch E As Exception

MsgBox("The file could not be read")

MsgBox(E.Message)

End Try

End Sub
 
J

Jim Underwood

First, remove the vbCRLF. I am not sure what the problem is, but the line
feed will definately not help.

You are adding a string to a collection, and the line feed is ending up as
part of the string, not as a delimiter.

To be honest, the sytax of your items.add looks fine to me. It is the same
code I use to populate my listbox.

I would make one change, however. Strictly for code readability and
debugging, create a variable to hold your string and pass it to the listbox
items.add. Also write this value out to the console to make sure the
problem is not with the string itself.

dim strListBoxItem as string
strListBoxItem = line.Substring(0, (line.IndexOf(",")))
console.writeline("List box item = " & strListBoxItem)
lstNames.Items.Add(strListBoxItem )
 
P

Patrick Sullivan

Thanks Jim, good idea about the console output testing. I have never used
file reading with VB before, other than databases, so I just cobbled
together what I thought would work. Seems like C/C++ was so much easier.
 
P

Patrick Sullivan

Now I feel dumb. I was using some control called listview instead of
listbox. Now it works fine. Thanks!
 

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