如何从名称的列表框中加载文本文件在visual basic中是未知的

时间:2014-06-01 10:32:53

标签: vb.net

所以坐在这里尝试打开这个基本上我有两个列表框,第一个是选择列表,如果你单击其中一个选项,它会拉出一个文件列表并将它们放入listbox2。

现在我正在努力研究如何在列表框中打开文件,如果选择了一个文件夹中的文件。

这是我到目前为止所做的,但是列表框2不起作用:

Private Sub ListBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ListBox1.SelectedIndexChanged
    If ListBox1.Text = "Custom" Then
        Dim folderInfo As New IO.DirectoryInfo("C:\Users\A\Desktop\Project1\Project1\My Project\Responses\Custom")
        Dim arrFilesInFolder() As IO.FileInfo
        Dim fileInFolder As IO.FileInfo
        arrFilesInFolder = folderInfo.GetFiles("*.*")
        For Each fileInFolder In arrFilesInFolder
            ListBox2.Items.Add(fileInFolder.Name)
        Next

    End If
End Sub

Private Sub ListBox2_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ListBox2.SelectedIndexChanged
    Dim myfile As String = Dir$("C:\Users\A\Desktop\Project1\Project1\My Project\Responses\Custom\*.*")

    'Check if file exists
    If System.IO.File.Exists(myfile) = True Then
        'Read the file
        Dim objReader As New System.IO.StreamReader(myfile)

        'Save file contents to textbox
        RichTextBox1.Text = objReader.ReadToEnd
        objReader.Close()
    Else
        MsgBox("File not found!")
    End If
End Sub

结束班

提前致谢。

1 个答案:

答案 0 :(得分:0)

您的Listbox2子应如下所示:

Private Sub ListBox2_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ListBox2.SelectedIndexChanged
    Dim myfile As String = "C:\Users\A\Desktop\Project1\Project1\My Project\Responses\Custom\" & ListBox2.SelectedItem

    'Check if file exists
    If System.IO.File.Exists(myfile) = True Then
        'Read the file
        Dim objReader As New System.IO.StreamReader(myfile)

        'Save file contents to textbox
        RichTextBox1.Text = objReader.ReadToEnd
        objReader.Close()
    Else
        MsgBox("File not found!")
    End If
End Sub

更具体地说,您的myfile应由路径和列表框选定项目组成,即文件名。

所以:

enter image description here