从文件加载到列表框?

时间:2011-06-08 01:53:25

标签: vb.net button listbox load text-files

所以在我的程序中,我试图让它按下按钮打开一个“选择文件”弹出窗口(用户可以选择文本文件),然后在用户选择后,程序将自动加载每个将文本文件的行放入列表框中。

但我一直在研究它,我唯一能找到的就是文件>开放的东西。因此,按下按钮

让它打开一个“开放式”对话有多冷

因为我无法在开放式对话框中找到任何内容,所以我没有找到任何关于将它的每一行加载到列表框中的内容,所以如果有人想要帮助我,那就太棒了。

我没有任何代码可以显示,因为我的程序的其余部分与此

无关

3 个答案:

答案 0 :(得分:2)

    Using FD As New OpenFileDialog()
        FD.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*"
        If FD.ShowDialog = Windows.Forms.DialogResult.OK Then
            Listbox1.Items.Clear
            ListBox1.Items.AddRange(IO.File.ReadAllLines(FD.FileName))
        End If
    End Using

编辑:回答评论:

如果你可以使用LINQ,那么它就是一行代码来读取列表框中的所有行并将其写入文件:

使用SaveFileDialog和LINQ

保存
    Using FD As New SaveFileDialog()
        FD.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*"
        If FD.ShowDialog = Windows.Forms.DialogResult.OK Then
            IO.File.WriteAllLines(fd.filename, (From p As String In ListBox1.Items Select p).ToArray)
        End If
    End Using

如果你不能使用LINQ,那么你可以这样做:

使用SaveFileDialog和FOR / EACH

保存
     Using FD As New SaveFileDialog()
        FD.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*"
        If FD.ShowDialog = Windows.Forms.DialogResult.OK Then
            Dim FileContent As String = ""
            For Each i As String In ListBox1.Items
                FileContent &= i & vbCrLf
            Next
            IO.File.WriteAllText(FD.FileName, FileContent)
        End If
    End Using 

答案 1 :(得分:0)

基本上,这里有几个部分。首先,您要创建一个“打开文件”对话框,提示用户输入文件的位置。这是你如何做到的:

http://www.homeandlearn.co.uk/net/nets4p6.html

接下来,您希望逐行读取文本文件到列表框中。以下是您阅读文本文件的方法(您需要修改代码以将其添加到列表框而不是执行Console.WriteLine:

http://msdn.microsoft.com/en-us/library/db5x7c0d.aspx

答案 2 :(得分:0)

OpenFileDialog from MSDN

   Private Sub button1_Click(ByVal sender As Object, ByVal e As System.EventArgs)
        Dim myStream As Stream = Nothing
        Dim openFileDialog1 As New OpenFileDialog()

        openFileDialog1.InitialDirectory = "c:\"
        openFileDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*"
        openFileDialog1.FilterIndex = 2
        openFileDialog1.RestoreDirectory = True

        If openFileDialog1.ShowDialog() = System.Windows.Forms.DialogResult.OK Then
            Try
                myStream = openFileDialog1.OpenFile()
                If (myStream IsNot Nothing) Then
                    ' Insert code to read the stream here.
                End If
            Catch Ex As Exception
                MessageBox.Show("Cannot read file from disk. Original error: " & Ex.Message)
            Finally
                ' Check this again, since we need to make sure we didn't throw an exception on open.
                If (myStream IsNot Nothing) Then
                    myStream.Close()
                End If
            End Try
        End If
    End Sub

从评论中可以看出,您可以在用户打开文件后阅读流。然后,您可以使用例如StreamReader来读取此流。这将为您提供用户选择的文件中的数据。根据您的需要,您可以解析该数据并将其添加到列表框中。

相关问题