Bon Journey
Bon Journey

Reputation: 21

How do I insert data from a text file into a 2D Array in VB.Net?

Currently I have these data inside my textfile.txt:

data in txtfile

I want to split them up into a 2D array when a comma is met. How do I do so?

This is my code for now. Please do point out the mistakes I made.

Dim priceArray(5, 2) As String
Dim i, j As Integer
Dim data As String
Dim oilpriceFile As System.IO.StreamReader 
oilpriceFile = New System.IO.StreamReader("C:\Users\zack\OneDrive\Desktop\oilprice.txt")
        
For i = 0 To UBound(priceArray)
      data = oilpriceFile.ReadLine()
      For j = 0 To UBound(priceArray)
          priceArray(i, j) = data.Split(",") //there's an error stating "value of type string() cannot be converted into string"
          j = j + 1
      Next
      i = i + 1
Next

Upvotes: 0

Views: 580

Answers (1)

Mary
Mary

Reputation: 15091

There are several things you are doing incorrectly.

First turn on Option Strict in the Project Properties and also under Options on the Tools menu.

You do not declare the increment variables used in For loops.

StreanReader needs to be disposed. You should know this because you always check the documentation before you use an unfamiliar framework class. When you do this you will see a Dispose method. When you see this, it needs to be called when you are through with using it. See Using...End Using.

You don't have to deal with Dispose if you use File.ReadAllLines(). This returns an array of the lines in the file.

A For loop increments the value of the first variable automatically. You do not increment it explicitly or you will skip values.

You have defined a 2 dimensional array. When you call UBound on the array, which dimension are you calling it on?? You must indicate which dimension you are asking about.

UBound(priceArray, 1) and UBound(priceArray, 2)

Where 1 and 2 designate the dimension you are getting.

This is the old vb6 way to get this value. The .net framework provides GetUpperBound() for the same purpose. This method uses the .net zero based rank where GetUpperBound(0) will return upper bound of the first dimension of the array.

The next problem is the use of Spilt. Split returns an array of strings and you are trying to assign it to a single string. It takes a Char as a parameter. You have passed a String. To tell the compiler that you intend a Char follow the String by a lower case c.

A side note. // is the comment indicator in C#. In vb.net use the single quote '.

Private Sub OPCode()
    Dim priceArray(5, 2) As String
    Dim lines = File.ReadAllLines("C:\Users\zack\OneDrive\Desktop\oilprice.txt")
    For i = 0 To priceArray.GetUpperBound(0)
        Dim data = lines(i)
        Dim splits = data.Split(","c)
        For j = 0 To priceArray.GetUpperBound(1)
            priceArray(i, j) = splits(j)
        Next
    Next
End Sub

Upvotes: 1

Related Questions