-
textfile to listbox
I am having trouble getting items from a text file to show up when my form opens immediately. I have done this before with a .csv file and thought it would be similar, but it hasn't worked. I've tried the codes used by my other classmates and I still can't get it to show up in my list box. Basically the form has a menu bar with a few options on it and then a huge list box filling the rest.
And this is the code I've tried:
Structure invdetails
Dim title As String
Dim author As String
Dim category As String
Dim price As Double
Dim quantity As Integer
End Structure
Private Sub lstBox_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles lstBox.SelectedIndexChanged
Dim inventory() As invdetails
Dim books() As String = File.ReadAllLines("Books.txt")
Array.Sort(books)
Dim n As Integer = books.Count - 1
ReDim inventory(n)
Dim line As String
Dim data() As String
For i As Integer = 0 To n
line = books(i)
data = line.Split(","c)
inventory(i).title = data(0)
inventory(i).author = data(1)
inventory(i).category = data(2)
inventory(i).price = CDbl(data(3))
inventory(i).quantity = CInt(data(4))
Next
For i As Integer = 0 To n
lstBox.Items.Add(inventory(i).title)
Next
End Sub
Also:
Dim reader As IO.StreamReader = New IO.StreamReader(New IO.FileStream("books.txt", IO.FileMode.Open))
Do While Not reader.EndOfStream
lstBox.Items.Add(reader.ReadLine())
Loop
Also:
'Gets hardcoded text file
Dim books As String = "books.txt"
'Open filestream
Dim booksfs As IO.FileStream = New IO.FileStream(books, IO.FileMode.Open)
'Open streamreader
Dim bookssr As IO.StreamReader = New IO.StreamReader(booksfs)
'Display contents of txt file in list box
For Each item As String In "books.txt"
lstBox.Items.Add(item)
Next
'Close streamreader
bookssr.Close()
'Close filestream
booksfs.Close()
These are a few I have tried and none of these have gotten the text file to open immediately in the list box when it opens. I can't get them to show up at all actually.
The text file is Title, Author, Fiction or Non Fiction, Stock Amount, and Price
Any help would be appreciated!
-
Re: textfile to listbox
What's the point of putting this in the selected index changed event? The ListBox has no items, so nothing can be selected, so the selected index won't be changed. Loading a listbox within an event of the listbox makes no sense at all. It's liking asking an orange to eat itself!
Initialisation of controls is usually done in the start-up form's Load event (occasionally in the Shown event) for obvious reasons. Go and do thou likewise!
-
Re: textfile to listbox
Thank you! That was the problem plus several others that your tip helped me find out. Thank you!