tags:

views:

65

answers:

2

What I wanted to do was create a listbox from a delimited text file.

The listbox would populate X # of rows based on the rows of the text file. And the listbox would have 3 columns, each being populated from a specific delimiter. Is this possible in C#? Any starting point would be great!


Hmm, i need to work on my explaination skills. What i'm wondering is if its possible to make a listbox with column and row lines in it?

+1  A: 

If you want more than one column, you need to use a ListView instead of a ListBox.

ListView lv = new ListView();
using (FileStream fs = new FileStream(@"c:\whatever.txt", FileMode.Open))
{
    StreamReader reader = new StreamReader(fs);
    while (!reader.EndOfStream)
    {
        string line = reader.ReadLine(); // e.g. "BOB|SMITH|JR."
        string[] coldata = line.Split('|');
        ListViewItem item = new ListViewItem(coldata);
        lv.Items.Add(item);
    }
}

Note: when you place the ListView on your form, set the mode to Details and add however many column headers you need.

MusiGenesis
+1  A: 

I suggest you using ListView (also set details view, and add header with three columns).

private void addLineToListView(String col1Text, String col2Text, String col3Text)
    {
        ListViewItem lvItem;
        if ((lvItem = this.listView1.Items.Add(col1Text)) != null)
        {
            lvItem.SubItems.Add(col2Text);
            lvItem.SubItems.Add(col3Text);
        }
    }

for loading file it's simple as well:

  private void AggregateTextFileIntoListView(String pathToFile)
  {
      using (TextReader tr = new StreamReader(pathToFile)))
            {
                String line;
                while ((line = tr.ReadLine()) != null)
                {
                    //* let's delimiter be ";".
                    String[] lineParts = line.Split(';');
                    addLineToListView(lineParts[0], lineParts[1], lineParts[2]);
                }

                tr.Close();
            }
 }
Lukas Šalkauskas
Thank for the tips, i tried out the code and it only populated with column 0 for some reason, it did this:0|0|0 instead of0|1|2
Mike