vb.net Reading from a .txt file and displaying the contents

那年仲夏 提交于 2019-12-07 02:11:24

A ListBox is not for displaying text, but displaying lists (as the name suggests). If you want to display text, use a TextBox. Since it is likely that the file will contain multiple lines, you can set the .Multiline property to True, so that the TextBox will display it correctly.

Furthermore, you should use the using statement when dealing with Streams

Dim content As String = ""
Using textReader As New System.IO.StreamReader(openTxt.FileName)
  content = textReader.ReadToEnd
End Using
displayForm.ListBox1.Text = content

or simply use the System.IO.File.ReadAllText("path to file here") command.

Do you want to read the file line-by-line and populate the listbox control?

If that's the case then try this function

Function ReadFile(ByVal Filename As String) As String()
    Dim Sl As New List(Of String)
    Using Sr As New StreamReader(Filename)
        While Sr.Peek >= 0
            Sl.Add(Sr.ReadLine())
        End While
    End Using
    Return Sl.ToArray
End Function

And use like so:

    For Each Line As String In ReadFile("FILENAME.txt")
        ListBox1.Items.Add(Line)
    Next
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!