Question

I need some help with loading text file into a listView. Text file looks like this:

1,6 sec,5 sec,1 sec,17,
2,6 sec,4 sec,2 sec,33,
3,7 sec,5 sec,3 sec,44,

I have to load this into a listView control and every subitem should be separated by comma (or any other character). I tried something like this:

using (var sr = new StreamReader(file))
{
   string fileLine = sr.ReadLine();
   foreach (string piece in fileLine.Split(',')) 
   {     
      listView1.Items.Add(piece); 
   } 
   sr.Close(); 
}

it would work just fine apart from only first line is loaded to the first column in listview. I cannot figure it out.

Thanks for your time! KR!

Was it helpful?

Solution

You have to advance to the next line, you can use a while-loop:

using (var sr = new StreamReader(file))
{
    string fileLine;
    while ((fileLine = sr.ReadLine()) != null)
    {
        foreach (string piece in fileLine.Split(','))
        {
            listView1.Items.Add(piece);
        }
    }
}

Note that you don't need to close the stream manually, that is done by the using-statement.

Another way is using File.ReadLines or File.ReadAllLines which can help to simplify your code:

var allPieces = File.ReadLines(file).SelectMany(line => line.Split(','));
foreach(string piece in allPieces)
    listView1.Items.Add(piece);

OTHER TIPS

using (var sr = new StreamReader(file))
{
     while(!sr.EndOfStream)
     {
          string fileLine = sr.ReadLine();
          foreach (string piece in fileLine.Split(',')) 
          {     
              listView1.Items.Add(piece); 
          } 
          sr.Close(); 
     }
}

Ι guess you just have to add:

while (!sr.EndOfStream)
{
                string fileLine = sr.ReadLine();
                foreach (string piece in fileLine.Split(',')) 
                {     
                        listView1.Items.Add(piece); 
                } 
}

sr.Close();// close put the end of while scope beacause you have a multiline text this code can't be read second line, and throw exceptions this code.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top