Phoenix
Phoenix

Reputation: 1931

Read Multiple Files Into List View VB.Net

I need to require the user of this program to select two text files from any directory. I then need to display them in a List View, which I have built. File 1 needs to load into the first column and File 2 needs to load into the second. They will correspond to each other.

I currently have the following to allow multiselect

OpenFileDialog.Multiselect = True

What I am having trouble with is separating these unique files into corresponding columns. For example, the following code very effectively loads the first file's contents into the first column:

        Dim fileName As String = OpenFileDialog.FileName

        fileReader = New StreamReader(fileName)

        Do While fileReader.Peek() <> -1
        firstFile = fileReader.ReadLine & vbNewLine
        ListView1.Items.Add(firstFile)

        Loop

When I choose the second file, the first file's contents are replaced within the same column by the second file's contents.

I have looked at using an array, but am unsure how to load the unique files into each index.

I'm not really sure where to go from here.

Upvotes: 0

Views: 5762

Answers (1)

Nick
Nick

Reputation: 1128

When you use

OpenFileDialog1.Multiselect = true

All selected files are already stored as a collection in OpenFileDialog1.FileNames, just loop through all values and put them into the listview

ListView1.Items.Clear
Dim file as string
For Each file in OpenFileDialog1.FileNames
    ListView1.Item.Add(file)
Next

if you want to show the file content in different columns, then you may need to change a little bit of your code

    Dim fileName As String = OpenFileDialog.FileName

    fileReader = New StreamReader(fileName)

    Dim FileItem As New ListViewItem
    Do While fileReader.Peek() <> -1
        firstFile = fileReader.ReadLine & vbNewLine

        FileItem .SubItem.Add(firstFile)

    Loop
    ListView1.item.add(Item)

However you may need to declare the columns in the ListView1 before adding any item. If not columns define in your ListView1, then it is not possible to show the columns even you have put your file content into the subItem

Upvotes: 3

Related Questions