'Reading from text file to ListBox

I am having a bit of trouble reading data from a text file. This almost works, however data in separate lines in the text file is combined to one long line in the ListBox. How else to do it?

Private Sub frmOpretrskAar_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    Dim FILE_NAME As String = "c:\users\claus\onedrive\SLERP\fmr.txt"
    Dim objReader As New System.IO.StreamReader(FILE_NAME)
    LBmuligeFirmaer.Items.Add(objReader.ReadToEnd)
    objReader.Close()
End Sub


Solution 1:[1]

Use the ListBox.Items.AddRange method to add an array, in this case it would be an array that represents the lines of the text file. You can get the lines by using IO.File.ReadAllLines method. Here is a quick example:

LBmuligeFirmaer.Items.AddRange(IO.File.ReadAllLines("c:\users\claus\onedrive\SLERP\fmr.txt"))

Solution 2:[2]

Its very simple -

List<string> _list = File.ReadAllLines(fileName).ToList();

See the below image -

enter image description here

Solution 3:[3]

You can use array. Try this code:

   Dim FILE_NAME As String = "c:\users\claus\onedrive\SLERP\fmr.txt"
   Dim AllLines() As String = System.IO.File.ReadAllLines(FILE_NAME)
   For i As Integer = 0 To AllLines.Count - 1
       LBmuligeFirmaer.Items.Add(AllLines(i))
   Next

Solution 4:[4]

I can't test this in my IDE currently so tell me if something doesn't work right but I have used something similar:

Imports System.IO
Imports System.Windows.Forms

'assigning a string value to the file's location
Dim FILE_NAME As String = "c:\users\claus\onedrive\SLERP\fmr.txt"

'clearing the listbox
LBmuligeFirmaer.items.clear

'declaring a filereader
Dim fileReader As System.IO.StreamReader
fileReader =       
'obtaining file location from string to the stringreader    
My.Computer.FileSystem.OpenTextFileReader(FILE_NAME)
Dim stringReader As String
'reading first line
stringReader = fileReader.ReadLine()
'adding line to the listbox
LBmuligeFirmaer.items.add(stringreader)
'reading second line
stringReader = fileReader.ReadLine()
'adding line to listbox
LBmuligeFirmaer.items.add(stringreader)

'and so on...

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Sandy
Solution 3 Mustafa Bazghandi
Solution 4 BuddyRoach