The Windows Forms ListView is designed to display data. You can use a simple text file as the data source of a Windows Forms ListView. Let's start with a scenario where you have a txt file that contains the data. Each line of the text file represents one row of data to be displayed in the ListView. The content for each column item (or cell) is delimited by the use of a TAB character.
A simple text file along these lines might contain the following entries:
Ged Mead UK
Serge Baranovsky USA
Larry Blake USA
Scott Waletzko USA
Mark Dryden UK
Dave Jeavons UK
Chris Manning USA
(The uneven layout is caused by the use of the TAB as the delimiter)
Reading data from a file
An easy way of transferring this data from the file to the ListView is to:
- Use a StreamReader which accesses the text file and then reads it line by line.
- As each new line is read, it is split by means of the TAB character and temporarily stored in a String array.
- Next, the first element is pulled out of the String array and used as the item for the first column of the ListView (the ListViewItem).
- Then the remaining two elements are pulled out of the String array in turn and assigned as the SubItems of the ListViewItem.
Here's the code that carries out those steps:
' Variable for file to hold data
Dim TextFile As String = "F:\MVPs.txt"
Private Sub btnGet_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnGet.Click
Try
' Declare StreamReader and pass the Path of the text file to be read as a Parameter
Dim SR As New StreamReader(TextFile)
' Variable to hold data as it is read line by line
Dim strTemp() As String
Do While SR.Peek <> -1 ' Use Peek to read the file until there are no more lines
' Create a variable for the ListViewItems
Dim LVItem As New ListViewItem
' Read the next line in file and Split it using the TAB.
strTemp = SR.ReadLine.Split(Chr(9))
' Pull out the first element in the line and assign it as
' the data for the first column.
LVItem.Text = strTemp(0).ToString
' Add the item to the ListView
LVMVPs.Items.Add(LVItem)
' Assign elements 2 & 3 as the subitems.
LVItem.SubItems.Add(strTemp(1).ToString)
LVItem.SubItems.Add(strTemp(2).ToString)
Loop
SR.Close() ' Close the StreamReader
Catch ex As Exception
MsgBox("Error reading file." & ex.Message)
End Try
End Sub
You'll see that I've used a variable to hold the path to the file that contains the data. You will also need to include an Imports statement for System.IO at the top of the Class file.
Although the above code will successfully access the file, read and split the data and then populate the ListView, the result you will see may not be what you expect or want:

The first problem is that the View Property of the ListView needs to be set to Details. By default it is set to LargeIcon, with the result you see in the screenshot. You can make this change via the Properties Window or in code.
LVMVPs.View = View.Details
Make that change, run the project, hit the 'Get From File' button and you will see:

Again, definitely not what you want! The problem here is that the ListView won't automatically create columns for you, even though you might expect that it would based on the data you are feeding in. As it is traditional to have some header text at the top of each column, you can create this at the same time as you create the column itself .
LVMVPs.Columns.Add("First Name", 76)
LVMVPs.Columns.Add("Surname", 96)
LVMVPs.Columns.Add("Location", 56)
Now, when you run the project again you will see the data neatly tabulated in the ListView.

I have also set the width property of each column in the code above, because the default width would result in some of the longer strings being truncated otherwise.
If you don't want to hard code those column headers, you can change the text file structure and have the column headers written to the first line of the file. You would then pull these out first and assign them to the columns, before using the Do While loop to read and display the rest of the file.
Writing data to a file
Although a ListView's key purpose is to display existing data, there may be times when you have edited the content and want to save it back to a text file. The steps involved in doing this are as follows:
- Use a FileStream to set up the file you are going to write to.
- Use a StreamWriter to access the chosen file.
- Loop through each row of the ListView, pull the text data from each column in turn and write it to the text file, adding a TAB character after each item.
- Add a new line at the end of each loop.
The code for this process is:
Private Sub btnSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSave.Click
' Create FileStream and StreamWriter to access and write to file
Dim FS As New FileStream(TextFile, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite)
Dim SW As New StreamWriter(FS)
Try
' Loop through all rows
For Index As Integer = 0 To LVMVPs.Items.Count - 1
' Internally loop through all columns, gathering items
For SubIndex As Integer = 0 To LVMVPs.Items(Index).SubItems.Count - 1
SW.Write(LVMVPs.Items(Index).SubItems(SubIndex).Text & Chr(9))
Next
' Create new line ready for next row
SW.Write(Environment.NewLine)
Next
Catch ex As Exception
MsgBox("Error saving to file." & ex.Message)
Finally
SW.Close()
FS.Close()
End Try
End Sub
For many simple scenarios where you want to display tabulated text in a ListView (and optionally save it back to a file), the above approaches will work just fine. There will of course be times when you need something more sophisticated and I will look at some of those in later blogs.