steloshow
steloshow

Reputation: 5

Loading a tab delimited textfile and displaying it in a listview c#

in VS2010, c# windows form. I am attempting to load and display (read) a textfile ("booklist.txt") which is currently in my bin\Debug folder, it is tab delimited, into a multicolumn listview. I tried a foreach loop foreach(string ya in arrayname) and it seemed to populate something as the listview expanded but didnt show anything and froze the program. EDIT: with the proper adding, I am getting the first record in the text to populate the LV, but no others. The records are separated by new line, and tab delimited for the different fields/info to go into each column.

    static FileStream textFile = new FileStream("booklist.txt", FileMode.OpenOrCreate, FileAccess.ReadWrite);
    StreamReader reader = new StreamReader(textFile);
    string[] booksTextArray;
    private void LoadButton_Click(object sender, EventArgs e)
    {
        // loads text file with existing book catalog
        string recordIn = reader.ReadLine();
        booksTextArray = recordIn.Split('\t');
        for (int i = 0; i < booksTextArray.Length; i++)
        {
            listView1.Items.Add(booksTextArray[i]);
        }
    }

Upvotes: 0

Views: 3148

Answers (1)

hatcyl
hatcyl

Reputation: 2352

Here is the general algorithm you can use:

//Holders.
string line = "";
string[] items;
ListViewItem listItem;

//While there are lines to read.
while((line = reader.ReadLine()) != null)
{
    items = line.Split('\t') //Split the line.
    listItem = new ListViewItem(); //"Row" object.

        //For each item in the line.
        for (int i = 0; i < items.Length; i++)
        {
            if(i == 0)
            {
                listItem.Text = items[i]; //First item is not a "subitem".
            }
            else
            {
                listItem.SubItems.Add(items[i]); //Add it to the "Row" object.
            }
        }

    listView1.Items.Add(listItem); //Add the row object to the listview.
}

Upvotes: 1

Related Questions