BLINKOR
BLINKOR

Reputation: 31

Reading a specific value in a cell in a .csv file in VB.NET

My goal is to find a specific value of a cell in a .csv file. (it is best not to use any extra reference packages) For example, if I have a .csv file that looks like this:

A, B, C, D
E, F, G, H
I, J, K, L
M, N, O, P

Then I want to return the value of the specific cell on row 2 and column 3, which is G

I've tried this code:

 Dim sData() As String
   
        csvPath = appPath & "/sample.csv" 
        Using sr As New StreamReader(csvPath)
            Dim counter As Integer = 0
            While Not sr.EndOfStream
                sData = sr.ReadLine().Split(","c)
                If counter > 2 Then
                    Dim Cell1 As String = sData(0).Trim()
                 
                    MessageBox.Show(Cell1)
                    TextBox1.Text = Curdate
                    TextBox2.Text = OrderId
                End If
                counter += 1


            End While
        End Using

What happens is that when this code is run, a messagebox pops up and lists every single row of the .csv file. What happens with textboxes is that it displays the final row in the csv file.

How can I make this to only return the specific value of one cell in a .csv file when given the row number and the column number?

Upvotes: 1

Views: 1381

Answers (2)

Idle_Mind
Idle_Mind

Reputation: 39142

Here's an example of loading that file into memory and storing it for repeated access:

Private data As New List(Of String())

Private Sub LoadData() ' call it ONCE (maybe from the Load() event?)
    data.Clear()
    csvPath = appPath & "/sample.csv"
    Using sr As New StreamReader(csvPath)
        While Not sr.EndOfStream
            data.Add(sr.ReadLine().Split(","c))
        End While
    End Using
End Sub

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    ' these are one based values
    Dim row As Integer = 2
    Dim col As Integer = 3
    Dim value As String = GetCellValue(row, col)
    If Not IsNothing(value) Then
        MessageBox.Show(row & ", " & col & " = " & value)
    Else
        MessageBox.Show("Invalid Row/Col!")
    End If
End Sub

Private Function GetCellValue(ByVal row As Integer, ByVal col As Integer) As String
    If row >= 1 AndAlso row <= data.Count Then
        Dim arr As String() = data(row - 1)
        If col >= 1 AndAlso col <= arr.Length Then
            Return arr(col - 1)
        End If
    End If
    Return Nothing
End Function

Upvotes: 3

Steve
Steve

Reputation: 216313

If your CSV file is not very big, the simplest way is to load everything in a memory list and then extract the required information

Function GetValue(row As Integer, col As Integer) As String
    
    Dim csvPath = "/sample.csv"
    Dim result As String = String.Empty
    Dim lines = File.ReadAllLines(csvPath)
    If row < lines.Length Then
        Dim cols = lines(row).Split(","c)
        If col < cols.Length Then
            result = cols(col)
        End If
    End If
    Return result        
End Function

However pay attention to two things.

  1. The file should not be very big because this code loads it completely in memory.
  2. Be sure to not call this in a loop because every time you call the method this reloads all the data from disk. In that case think about creating a class where you load the file just one time at initialization and then call the GetValue method working with the loaded data.

Upvotes: 3

Related Questions