Search code examples
c#listboxstreamreader

StreamReader to multiple listboxes


I am attempting to use the StreamReader to break data from a text file into multiple listboxes. Thus far, I 've been able to get all the data into one listbox, but the next step of my project requires the data to be split and I think I understand listboxes better than arrays. I have made an effort to search for a similar problem, but because I am a beginner, most of what I have found perplexes me further. I have only been able to accomplish the following successfully:

StreamReader file = new StreamReader(openFileDialog1.FileName);
string data;
while (!file.EndOfStream)
{
    data = file.ReadLine();
    listBox1.Items.Add(data);
}
file.Close();

My data in my .txt file comes in blocks of three like so:

blue
david
8042
red
joseph
7042

I am unable to change the data format, so I have been trying to code it out in such a way that

if (blue)
    listBox1.Items.Add(david);
    listBox2.Items.Add(8042);
else if (red)
    listBox3.Items.Add(joseph);
    listBox4.Items.Add(7042);

etc. I only have two colors to work with, but lots of data for each of those colors. My problem is that I am new to coding and failing to put into place the basics I've learned to do such a thing.

What are the lines of code I'm missing to add a line below a line to a listbox while it StreamReads? Do I need to use an

int counter = 0;

and increase it by 1 or 2 to get those lines, or am I thinking too basically?

Thank you very much for any help. I feel like I'm missing something very simple I have yet to grasp.


Solution

  • One possible way out is reading by three lines (i.e. entire block) instead of one:

      using (StreamReader file = new StreamReader(openFileDialog1.FileName)) {
        while (!file.EndOfStream) {
          string color = file.ReadLine();
          string name = file.ReadLine();
          string number = file.ReadLine();
    
          if (color == "blue") {
            listBox1.Items.Add(name);
            listBox2.Items.Add(number);
          }
          else if (color == "red") {
            listBox3.Items.Add(name);
            listBox4.Items.Add(number);
          }
        }  
      }