JimmyTheProcess
JimmyTheProcess

Reputation: 11

How to create and populate a Datatable from a Txt file

I'm new to vb.net so i don't know wheather this question might sound stupid. I have a txt file in input and want to create a Datatable and populate it with the text file but for some reasons i'm not able to populate it. Here's my code:

Public Function TxtToCsv(ByVal txtPath As String)

    Console.ReadLine()
    Dim dt As DataTable = New DataTable

    dt.Columns.Add("1", GetType(String))
    dt.Columns.Add("2", GetType(String))

    Dim myString As String = File.ReadAllText(txtPath)
    Dim rows() As String = myString.Split({Environment.NewLine}, StringSplitOptions.RemoveEmptyEntries)

    For i As Integer = 1 To dt.Rows.Count - 1

        Dim dr As DataRow
        dr = dt.NewRow()

        dr(columnIndex:=0) = rows(i).Substring(0, 25)
        dr(columnIndex:=1) = rows(i).Substring(26, 8)

        i += 1

    Next

    Console.WriteLine(dt)
    Console.ReadLine()

Upvotes: 0

Views: 1223

Answers (2)

Mary
Mary

Reputation: 15091

Console.WriteLine(dt) will call .ToString on dt which returns the fully qualified name.

Sub Main()
    Dim dt As DataTable = FillDataTable("C:\Users\***\Desktop\TestData.txt")
    Console.Write(DataTableToString(dt))
    Console.ReadKey()
End Sub

Private Function FillDataTable(txtPath As String) As DataTable
    Dim dt As New DataTable
    dt.Columns.Add("1", GetType(String))
    dt.Columns.Add("2", GetType(String))
    'ReadAllLines returns and array of the lines in the text file
    Dim rows() As String = File.ReadAllLines(txtPath)
    'Start at zero, the index of the first line
    For i As Integer = 0 To rows.Length - 1
        Dim dr As DataRow
        dr = dt.NewRow()
        dr(columnIndex:=0) = rows(i).Substring(0, 5)
        dr(columnIndex:=1) = rows(i).Substring(7, 3)
        dt.Rows.Add(dr)
        'Your index is incremented by the For...Next loop
        'i += 1
    Next
    Return dt
End Function

Private Function DataTableToString(dt As DataTable) As String
    Dim sb As New StringBuilder
    For Each r As DataRow In dt.Rows
        For Each c As DataColumn In dt.Columns
            sb.Append(r(c).ToString & " ")
        Next
        sb.AppendLine()
    Next
    Return sb.ToString
End Function

Upvotes: 1

the_lotus
the_lotus

Reputation: 12748

You are looping the rows of the data table instead of the rows of the file.

For i As Integer = 1 To rows.length - 1

The for loop increases "I" automatically, remove the +=1

' i += 1

I don't think you can write line a datatable directly.

Console.WriteLine(dt) ' Find an other way to print the data

I suggest you turn Option Strict On. This will help you find errors. Also, write just a few lines at a time and test them.

Upvotes: 0

Related Questions