读取文本文件,然后将所有行添加到VB.NET中的列表框中

时间:2013-11-29 16:34:24

标签: vb.net

我桌面上有一个文本文件......

在这个档案中,我们有五行:

Line 1
Line 2
Line 3
Line 4
Line 5

如果用户选择此文本文件,则所有行(五行)都会添加到列表框项目中。

例如,我们在列表框中有这些(当用户选择文本文件(它有五行)时):

Line 1
Line 2
Line 3
Line 4
Line 5

3 个答案:

答案 0 :(得分:7)

试试这个:

Dim lines() As String = IO.File.ReadAllLines("C:\dir\file.txt")
ListBox1.Items.AddRange(lines)

More information is at MSDN

答案 1 :(得分:0)

Private Sub OpenList()
    Dim openfile = New OpenFileDialog()
    openfile.Filter = "Text (*.txt)|*.txt"
    If (openfile.ShowDialog() = System.Windows.Forms.DialogResult.OK) Then
        Dim myfile As String = openfile.FileName
        Dim allLines As String() = File.ReadAllLines(myfile)
        For Each line As String In allLines
            listBox.Items.Add(line)
        Next
    End If
End Sub

答案 2 :(得分:-1)

使用:

Dim openfile = New OpenFileDialog() With {.Filter = "Text (*.Text)|*.txt"}
If (openfile.ShowDialog() = System.Windows.Forms.DialogResult.OK) Then
    For Each line As String In File.ReadAllLines(openfile.FileName)
        ListBox1.Items.Add(line)
    Next
End If

代码要好得多。