2013-05-30 42 views
0

我是想通過點擊一個按鈕,保存在硬盤驅動器上的列表中顯示的文件中的數據,但我不知道在山楂正確做到這一點:如何讀取文件並在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

回答

0

用途:

lstRecipes.Items.Add(TextLine.Text) 

更具體地說,它跳轉到列表中的下一個項目之前,因此這將您的TextLine轉讓後右轉。

2
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 
0

,你可以這樣做:

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 
相關問題