Tyler1621
Tyler1621

Reputation: 19

How to load data from a txt file into a listview in C# Windows Form

I am trying to load information from a text file into a list view. I know that it can be done, but I am having a hard time trying to figure out where I am going wrong. It does need to be a text file, and not a CSV, although the text is setup like a CSV. This is what I have so far...

private void Form1_Load(object sender, EventArgs e)
    {
        listView1.View = View.Details;
        listView1.Columns.Add("Name");
        listView1.Columns.Add("Address");
        listView1.Columns.Add("Age");
        listView1.Columns.Add("Gross Pay");
        listView1.Columns.Add("Division");

        // Auto-size the columns
        for (int i = 0; i < listView1.Columns.Count; i++)
        {
            listView1.Columns[i].Width = -2;
        }
    }
 private void ListView1_SelectedIndexChanged(object sender, EventArgs e)
        {
            var fileLines = File.ReadAllLines(@"C:\data.txt");

for (int i = 0; i + 4 < fileLines.Length; i += 5)
            {
                listView1.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 < listView1.Columns.Count; i++)
            {
                listView1.Columns[i].Width = -2;
            }
        }
    }
}

Currently nothing displays in the form, not even the blank List View. I have looked all over this site and tried to pick and pull from what other people have used, and nothing seems to fit what I am trying to do. Any help is very much appreciated. I am still pretty new to this language, but I am trying to learn.

Upvotes: 1

Views: 2470

Answers (1)

Casperonian
Casperonian

Reputation: 184

You can try the following. Condition is that the CSV file columns must match the list view columns.

listView.View = View.Details;
listView.Columns.Add ( "Name" );
listView.Columns.Add ( "Address" );
listView.Columns.Add ( "Age" );
listView.Columns.Add ( "Gross Pay" );
listView.Columns.Add ( "Division" );

List<string> data = File.ReadAllLines ( "TestCSV.txt" ).ToList ( );
foreach(string d in data)
{
    string[] items = d.Split(new char[] {','}, 
           StringSplitOptions.RemoveEmptyEntries);
     listView.Items.Add ( new ListViewItem ( items ) );                
}

Sample file content in CSV format but txt extension:

Name1,Address1,Age1,Gross Pay1,Division1,
Name2,Address2,Age2,Gross Pay2,Division2,
Name3,Address3,Age3,Gross Pay3,Division3,

If you allow blanks in the column. Then remove the condition:

StringSplitOptions.RemoveEmptyEntries

Upvotes: 1

Related Questions