Question

I created a program to load a text file, should load all lines from the textfile and display them in the listview

However It only loads the first line in the listview how do I get it to read the entire file?

Sub Loadbtn_Click(sender As System.Object, e As System.EventArgs) Handles Browse.Click
    OpenFD.ShowDialog()
    Dim Path As String = OpenFD.FileName
    Dim AllItems As String
    Try
        AllItems = My.Computer.FileSystem.ReadAllText(Path)
        Dim ItemLines As New TextBox
        ItemLines.Text = AllItems
        Dim lv As New ListViewItem
        For Each Line As String In ItemLines.Lines
            List.Items.Add(lv)
            lv.Text = Line
            lv.SubItems.Add(Crypto.AES_Decrypt(Line))
        Next
    Catch ex As Exception
    End Try
End Sub
Was it helpful?

Solution

One possible solution could look like this:

Sub Loadbtn_Click(sender As System.Object, e As System.EventArgs) Handles Browse.Click
    OpenFD.ShowDialog()
    ' full path to the file + name
    Dim filename As String = OpenFD.FileName
    Try
        ' check if file exists to prevent errors
        if (File.Exists(filename)) then
            ' fetch complete text into as lines
            Dim Lines = File.ReadAllLines(filename)
            ' iterate over each line
            For Each Line As String In Lines
                Dim lv as new ListViewItem
                ' take it
                lv.Text = Line
                ' and use it
                lv.SubItems.Add(Crypto.AES_Decrypt(Line))
                ' show it
                List.Items.Add(lv)
            Next
        end if
    Catch ex As Exception
        ' inform the user resp. developer
        Console.WriteLine(String.Format("An error occurred: {0}", ex.Message))
    End Try
End Sub

As already mentioned use File.ReadAllLines if you want to read the file line by line and don't suppress errors - inform the user or at least the developer (yourself, using a log file or something appropriate).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top