Question

I've been reading and reading tons of answers, modifying the code, and still i cant figure out how to solve this problem.

I have a textbox that receives multiline comma-separated information from a .txt or .csv file. Example:

Pearl Harbour;Ticonderoga CG-45;300;1000
Everett;Ticonderoga CG-46;310;1200
Pearl Harbour;Burke DDG-110;215;800

Now there will be a combobox to chose a port (in this example the options will be Pearl Harbour and Everett). After choosing "Pearl Harbour", another multiline textbox will show only the lines which have "Pearl Harbour" as the first element.

Now goes what I was able to write:

Public Sub Readfile()

TextBox1.Text = System.IO.File.ReadAllText("libro1.csv")<br>
Dim lines() As String<br>
lines = Split(TextBox1.Text, vbCrLf)<br>
Dim strline0 As String = lines(0)<br>
Dim strArray0() As String = strline0.Split(";")<br>
Dim strline1 As String = lines(1)<br>
Dim strArray1() As String = strline1.Split(";")<br>
...

End Sub

The first problem I find is that for every line the .csv has, I must write that two lines of code to have an array with all the information. But I cant do that because I cant know how many lines the .csv is going to have.

Im kind of lost here. Im not asking anyone to do magic and give me a code I can copy and paste, but I would be grateful if someone can guide me through this.

Was it helpful?

Solution

First off, you'd do better to use a List than an array. Particularly for a collection of strings, they're much easier to work with. With that, you're correct that you can't go individually naming your lines because you don't know how many there will be. That's why you need to create a list of lines and loop through them, like ...

Public Sub Readfile()
    TextBox1.Text = System.IO.File.ReadAllText("libro1.csv")
    Dim lines As List(of String)
    Dim allResults As New List(of List(of String))

    lines = Split(TextBox1.Text, vbCrLf)

    For Each line In lines
        Dim result As List(Of String) = line.Split(CChar(";"))
        allResults.Add(result)
    Next
End Sub

This will allow you to essentially say, "For each line in the file, take each semi-colon-separated part and put it into a list called 'result'. Then put 'result' into another list of results called 'allResults'."

Behold! The power of loops!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top