I need to read a text file into a ListView. I have already saved it to the file, but it doesn't seem that anyone has a good answer for reading the file back in. When the file reads in; all the data is in the first column and not in displayed under the appropriate headers.
Here is my text file data as it was saved to the file:
05 / 23 / 2017
10 : 44
13 : 44
3
$48.00
05 / 23 / 2017
09 : 15
15 : 15
6
$96.00
Here is the code I used:
private void ReadInTimeSheet()
{
foreach (string line in File.ReadAllLines(@"C:filepath\MyTimeSheet.txt"))
{
lvTimeSheet.Items.Add(new ListViewItem(line));
}
}
And here are the Results from the read in: Data displayed in ListView
In case you have problems opening the file; all the data is contained in the first column, and looks exactly as the view I have of the text in the file above.
What I need is the date displayed in column 1, start time in column 2, stop time in column 3, total hours worked in column 4, and how much pay the hours receive in column 5.
How can I achieve this? Thank you in advance.
First you should add columns to your list view, and make sure that the View
is set to Details
. Seting the column width to -2
will auto-size them:
private void Form1_Load(object sender, EventArgs e)
{
lvTimeSheet.View = View.Details;
lvTimeSheet.Columns.Add("Date");
lvTimeSheet.Columns.Add("Start Time");
lvTimeSheet.Columns.Add("Stop Time");
lvTimeSheet.Columns.Add("Total Hours");
lvTimeSheet.Columns.Add("Total Pay");
// Auto-size the columns
for (int i = 0; i < lvTimeSheet.Columns.Count; i++)
{
lvTimeSheet.Columns[i].Width = -2;
}
}
Then, when you read your file, you will need to read 5 lines, and add those five lines as a single ListViewItem
. Note that a ListViewItem
can be initialized with an array, so we'll just loop through your file lines, five lines at a time, create an array with those lines, and add a new ListViewItem
that's populated by that array:
private void ReadInTimeSheet()
{
var fileLines = File.ReadAllLines(@"C:\filepath\MyTimeSheet.txt"))
for (int i = 0; i + 4 < fileLines.Length; i += 5)
{
lvTimeSheet.Items.Add(
new ListViewItem(new[]
{
fileLines[i],
fileLines[i + 1],
fileLines[i + 2],
fileLines[i + 3],
fileLines[i + 4]
}));
}
// Resize the columns
for (int i = 0; i < lvTimeSheet.Columns.Count; i++)
{
lvTimeSheet.Columns[i].Width = -2;
}
}
Output