繁体   English   中英

你如何在VB.NET中读取文件并在列表框中显示?

[英]How do you read a file and display in listbox in VB.NET?

我试图通过单击按钮在硬盘驱动器上保存的列表中显示文件中的数据,但是我不确定如何正确地执行此操作:

Private Sub btnListRecipes_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnListRecipes.Click
    Dim TextLine As String
    If System.IO.File.Exists(Filename) = True Then
        Dim RecipeReader As New System.IO.StreamReader(Filename)
        Do While RecipeReader.Peek() <> -1
            TextLine = TextLine & RecipeReader.ReadLine() & vbNewLine
        Loop
        lstRecipes.Text = TextLine.Text
    Else
        MsgBox("File Does Not Exist")
    End If
End Sub

我真的很感激你的帮助:D

Private Sub btnListRecipes_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnListRecipes.Click
    Try
        lstRecipes.AddRange(File.ReadAllLines(FileName))
    Catch
        MsgBox("Unable to read file")
    End Try
End Sub

采用:

lstRecipes.Items.Add(TextLine.Text)

更具体地说,在它跳转到列表中的下一个项目之前,这将在您分配TextLine

你可以这样做:

Imports System
Imports System.IO

Public Class Form1

Public Shared listTXT, listOfTxt, listOfTxtFile As New List(Of String)

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

End Sub

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    Dim path As String = "C:\myDirectory\"

    Dim parentinfo As New DirectoryInfo(path)

    ' Store Text file name in a list
    For Each txtFile As FileSystemInfo In parentinfo.GetFileSystemInfos()
        listTXT.Add(txtFile.Name)
    Next

    ' Store Path of Text file in a list
    For noOfTxtFile = 0 To listTXT.Count - 1

        Dim pathOfFile As String = path & listTXT(noOfTxtFile)
        listOfTxtFile.Add(pathOfFile)

        Dim obj As System.IO.StreamReader
        obj = System.IO.File.OpenText(pathOfFile)

        While Not obj.EndOfStream
            listOfTxt.Add(obj.ReadLine)
        End While

    Next

    Dim lineOfTxt As Integer
    Dim txt As String

    For lineOfTxt = 0 To listOfTxt.Count - 1
        txt = listOfTxt(lineOfTxt)
        ListBox1.Items.Add(txt)
    Next
End Sub
End Class

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM