Hows it going everyone. Right now I am trying to read data from a text file into a datatable, and display the datatable in a new form. I am trying to use a string array to store the variables before adding them to the table. Everything compiles etc correctly, but when the new form with the datagrid that the table is bound to opens, there is nothing in the table.

Private Sub excludebtn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles excludebtn.Click
        Dim openFileDialog1 As New OpenFileDialog()
        openFileDialog1.Filter = "Text File|*.txt|Excel Spreadsheet|*.xls"
        openFileDialog1.Title = "Open File..."
        Dim line() As String

        Dim J As Integer = 0
        Dim K As Integer = 0
        If openFileDialog1.ShowDialog() = Windows.Forms.DialogResult.OK Then

            Dim myStream As System.IO.StreamReader = New System.IO.StreamReader(openFileDialog1.FileName)
            line = myStream.ReadToEnd.Split("\S+")

            Do While J < line.Count()
                Dim lStringReader As New System.IO.StringReader(line(J))
                J = J + 1

            Dim ex As exclude
            ex = New exclude

        End If

    End Sub

Maybe its possible but I never read code that used a stringreader to feed the DataRowCollections.Add Method. Typically a DataRow generated by the tables NewRow method or an array of objects is used as parameter.

If you read the datafields from a textfile and have other datatypes than "string" in the DataTable, you will need to convert these fields to the requested datatypes.

The example table has 2 String and 1 integer column, I used ";" as separator for the fields that make up one row.

Sample Datafile:

Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
        Dim tbl As New DataTable("mytable")
        tbl.Columns.Add("col1", GetType(String))
        tbl.Columns.Add("col2", GetType(String))
        tbl.Columns.Add("col3", GetType(Integer))
        Dim sFilename As String = "C:\TEMP\Dani\DataAccess\somedata.txt"
        Dim myStream As System.IO.StreamReader = New System.IO.StreamReader(sFilename)
        Dim line As String
        Dim aRow As DataRow
            line = myStream.ReadLine()
            If line Is Nothing Then
                Exit Do
            End If
            Dim sAry As String() = Split(line, ";")  ' separate the fields of the current row         
            aRow = tbl.NewRow 'get a DataRow that has the required structure
            aRow(0) = sAry(0)
            aRow(1) = sAry(1)
            aRow(2) = CInt(sAry(2))
        For Each aRow In tbl.Rows
            Console.WriteLine("{0} {1} {2}", aRow(0), aRow(1), aRow(2))

    End Sub
This article has been dead for over six months. Start a new discussion instead.