sark9012
sark9012

Reputation: 5737

Reading a text file

I am trying to achieve a situation where i load a file into the program. I can use streamreader for this. Each record will be 7 lines long. Therefore lines 1,8,15,22,etc will all hold the same value. As will 2,9,16,23, etc and so on.

What is the best way to achieve this? So that when i load the records in the listview, it recognises what i just said. Thanks

Upvotes: 2

Views: 467

Answers (3)

JDB
JDB

Reputation: 25810

Sounds like you need to create a class that will represent each record (one property for each of the 7 lines).

Open your stream reader.

Do, start looping while there are still lines to read.

For each iteration of your loop, read the 7 lines into seven variables, then create a new instance of your class and set each property to the value contained in the appropriate variable.

Add that class to a collection (List<MyClass>, for example).

Your ListView should use the collection of objects that you have constructed. You can now choose a property to act as the display value.

Upvotes: 1

Hans Olsson
Hans Olsson

Reputation: 55009

When you say that lines 1, 8, 15 etc will all hold the same value, do you actually mean that they hold the same type of value? Otherwise, why read in more than the first 7 lines?

I think something like the below might work (not tested the code).

string data;
using(System.IO.StreamReader reader = new System.IO.StreamReader("filepath"))
{
    data = reader.ReadToEnd();
}

string[] lines = data.Split(Environment.NewLine);

for(int index = 0; index < lines.Length; index += 7)
{
    ListViewItem item = new ListViewItem();
    for(int innerIndex = 0; innerIndex < 7; innerIndex++)
    {
        item.SubItems.Add(lines[index + innerIndex]);
    }

    listView1.Items.Add(item);
}

Upvotes: 3

Jared Forsyth
Jared Forsyth

Reputation: 13162

create a [num_lines/7] x [7] 2D array

for (int i=0;i<num_lines/7;i++)
    for (int t=0;t<7;t++)
        my2darray[i][t] = orig_array[i*7+t];

If i understand your question correctly, that will organize your data in the desired fashion

Upvotes: 0

Related Questions