Prasad MV
Prasad MV

Reputation: 107

How to add contents of a file to listview C#

The file name is contacts.txt. Its contents are:

line 1: Adam
line 2: [email protected]
line 3: Kris
line 4: [email protected]

I have a listview named listview1. It has 2 columns, ColumnHeader1 & ColumnHeader2

I want to add the name in the file to ColumnHeader1 and email to ColumnHeader2, i.e, like:

Adam    [email protected]
Kris    [email protected]

How do I do that?

Also, I want this to happen automatically every time the form is loaded.

Thank You in advance.

Tried this.

using (StreamReader sr = new StreamReader(@"C:\Contacts.txt"))
{
    while (sr.EndOfStream)
    {
        ListViewItem lvi = new ListViewItem(sr.ReadLine());
        lvi.SubItems.Add(sr.ReadLine());
        listView1.Items.Add(lvi);
        continue;
    }
    sr.Close();
}

Upvotes: 1

Views: 2434

Answers (1)

user153923
user153923

Reputation:

Take the continue word out. It shouldn't be necessary.

Try something like this:

using (StreamReader sr = new StreamReader(@"C:\Contacts.txt"))
{
  while (-1 < sr.Peek())
  {
    try
    {
      string name = sr.ReadLine();
      string email = sr.ReadLine(); 
      var lvi = new ListViewItem(name);
      lvi.SubItems.Add(email);
      listView1.Items.Add(lvi);
    } catch (Exception) { }
  }
  sr.Close();
}

That try/catch is there just in case there are not an even number of entries in your file.

Upvotes: 1

Related Questions