-1

I am trying to fill a listbox with the contents of a .csv file by separating the two values per line and add to a structure.

Public Class Form1

Structure Members
    Dim Number As Integer
    Dim Name As String
End Structure

Dim Memberlist(30) As Members

Public Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    Dim i As Integer = 0
    For Each line As String In IO.File.ReadAllLines("MembershipPhone.txt")
        Dim myData() = line.Split(","c)
        Memberlist(i).Name = myData(0)
        Memberlist(i).Number = myData(1)
        ListBox1.Items.Add(myData(0))
        i = i + 1
    Next
    ListBox1.SelectedItem = Nothing
End Sub
Grant Thomas
  • 44,454
  • 10
  • 85
  • 129
MrAlex42
  • 35
  • 1
  • 1
  • 6

1 Answers1

0

I see that you listed your question as C# when I think it may belong in VB.net. I can happily answer your question in C#....

First I would use a standard CSV reader. I find it to be easier and it can account for a bunch of different formats. I use the standard OleDbConnection and Microsoft JET engine to read to a database (How to read a CSV file into a .NET Datatable)

Once you have the Datatable you could bind it to your ListBox

//Load the data from the example above
DataTable myData = GetDataTableFromCsv(FilePath, true);

for (int i = 0; i < myData.Rows.Count; i++)
{
    //Grab all my data for this row
    string PersonID = (string)myData.Rows[i][0];
    string FirstName = (string)myData.Rows[i][1];
    string LastName = (string)myData.Rows[i][2];

    //Add what I want to the listbox
    ListBox1.Items.Add(FirstName);
}

//Select nothing from the listbox
ListBox1.SelectedIndex = -1;

Hope that was helpful! Good luck in .NET, it's a lot of fun, but I would recommend using C# over VB :-)

Community
  • 1
  • 1
mkamioner
  • 2,451
  • 1
  • 17
  • 14
  • thanks mkamioner. I'm taking a college course on VB so Im stuck using it. Much different than the c++ and python I'm use to so I'm ready to rip my hair out at this point. However, youve got me thinking a 2d array might be better suited over a structure here. – MrAlex42 Dec 04 '13 at 11:11