Textfieldparser from CSV file - need to put into a datatable or db and show user

Someone showed me textfieldparser, which is working great, I have used it to pull in data from a csv file.  I can pull it in a line at a time, but I am looking for some way to pull in all the data into a table and show to the user.  Listview?  Datagridview?  I was using Gridview but it is not available for a windows form.  I would like to show this data to the user, let them edit, delete rows, or add, then I will have to send this data to a txt file.  Trying to find a good way to do this and possibly make it look decent.  Thanks for any help in advance!  I have been googling for hours trying to find good methods.
LVL 3
ITSupermanAsked:
Who is Participating?
 
käµfm³d 👽Commented:
You could do something like this:

Imports Microsoft.VisualBasic.FileIO

Public Class Form1

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Using parser As New TextFieldParser("TextFile1.txt")
            parser.Delimiters = New String() {",", vbTab}
            parser.CommentTokens = New String() {"--"}

            Dim headers() As String = parser.ReadFields()

            For i As Integer = 0 To headers.Length - 1
                Me.DataGridView1.Columns.Add(headers(i), headers(i))
            Next

            While Not parser.EndOfData
                Dim fields() As String = parser.ReadFields()

                Me.DataGridView1.Rows.Add(fields)
            End While
        End Using
    End Sub
End Class

Open in new window

Untitled.png
0
 
nepaluzCommented:
you can use a textfield parser to populate a datagridview.
show us some code that you have (and the source data file if possible)

Also, what do you mean that the datagridview is not available for a windows form?
0
 
ITSupermanAuthor Commented:
I was referring to the ASP.NET Gridview which gives you options to change the template(easy to make it look better) - I couldn't find anything equivalent to that in Windows Form.  

I have attached the code I was working with thanks to another person on here.  Just need to stream it into a datagridview if that is the best way to work with the data.  Thanks again for the help!
Option Strict On

Imports System.Text

Public Class Form1

    Private Sub btnProcessDelimitedFile_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnProcessDelimitedFile.Click
        ProcessDelimitedFile()
    End Sub

    Private Sub ProcessDelimitedFile()
        'Provide a test file
        Dim strFile As String = IO.Path.Combine(Application.StartupPath, "TestDelimited.txt")

        'If a valid file path to a .txt file has been selected....
        If Not IO.File.Exists(strFile) Then
            MessageBox.Show("File does not exist!", _
                            "File not found", _
                            MessageBoxButtons.OK, _
                            MessageBoxIcon.Error)
            Return
        End If

        'Instantiate a reader with the file to process
        Dim reader As Microsoft.VisualBasic.FileIO.TextFieldParser = _
                My.Computer.FileSystem.OpenTextFieldParser(strFile)

        'Set the reader's TextFieldType to delimited 
        reader.TextFieldType = Microsoft.VisualBasic.FileIO.FieldType.Delimited
        'Set the readers Delimiters to a comma (,)
        reader.Delimiters = New String() {",", vbTab}
        'ignore the lines starting with this token
        reader.CommentTokens = New String() {"--"}

        ' Ready to read the file....
        Do While Not reader.EndOfData
            Try
                'Parse the line into fields using gthe ReadFields method
                Dim arrFields As String() = reader.ReadFields()

                'Process the data just read
                Dim strCurrentLine As String = String.Empty
                Dim t1 As Integer = 1
                Dim t2 As Integer = 2
                Dim tbox As String = "TextBox1"
                For Each strField As String In arrFields
                    strCurrentLine = strCurrentLine + strField + ";"
                    TextBox1.Text = strCurrentLine
                    TextBox2.Text = strField
                    t1 = t1 + 1
                    t2 = t2 + 1
                Next
                MessageBox.Show("The current line contains:" + _
                                Environment.NewLine + _
                                strCurrentLine, _
                                "Data read", _
                                MessageBoxButtons.OK, _
                                MessageBoxIcon.Information)

            Catch ex As Microsoft.VisualBasic.FileIO.MalformedLineException
                MessageBox.Show("Line " & ex.Message & _
                "is not valid and will be skipped.")
            End Try
        Loop

        'Close the reader
        reader.Close()
    End Sub

Open in new window

TestDelimited.txt
0
Cloud Class® Course: Amazon Web Services - Basic

Are you thinking about creating an Amazon Web Services account for your business? Not sure where to start? In this course you’ll get an overview of the history of AWS and take a tour of their user interface.

 
ITSupermanAuthor Commented:
That works great!  I am working on a button for the user to hit once they are done editing to send all of the datagridview to a text file with commas between fields now.
0
 
käµfm³d 👽Commented:
Cool. The example was intended to be very simple, so you'll note there is no error checking. You'll probably want to come up with a check for the column headers since the above code assumes the first row contains column headers.

I wasn't sure if you were asking or not, but I'll throw it out there  = )

Here is code which could  do the write:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    Using writer As New System.IO.StreamWriter("output.txt")
        For i As Integer = 1 To Me.DataGridView1.Rows.Count - 1
            Dim line As New System.Text.StringBuilder()

            For Each cell As DataGridViewCell In Me.DataGridView1.Rows(i).Cells
                If cell.Value IsNot Nothing Then
                    line.Append(cell.Value.ToString())
                End If

                line.Append(",")
            Next

            writer.WriteLine(line.ToString().Trim(","))
        Next
    End Using
End Sub

Open in new window

0
 
ITSupermanAuthor Commented:
Looks great!  I will be testing this tonight and will give you full points on it.  
0
 
käµfm³d 👽Commented:
NP. I need to make two slight corrections to it, though. Change line 14 to (yes, I'm changing one line to two):

line.Length -= 1
writer.WriteLine(line.ToString())

Open in new window


Previously, the Trim() call would have removed all trailing commas, even if there were empty fields. I don't believe you would want this. The change should only remove the last comma, by making the length of the StringBuilder one less than it was originally--effectively deleting the last character.

Also, the first non-header row is being left out and a blank row is being inserted. This is because of how I indexed the rows. Change line 3 to:

For i As Integer = 0 To Me.DataGridView1.Rows.Count - 2

Open in new window



If you want to include the column headers like they were in the original file, then you could modify the whole procedure to the following:

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    Using writer As New System.IO.StreamWriter("output.txt")
        Dim line As New System.Text.StringBuilder()

        For i As Integer = 0 To Me.DataGridView1.Columns.Count - 2
            line.Append(Me.DataGridView1.Columns(i).HeaderText)
            line.Append(",")
        Next

        line.Length -= 1
        writer.WriteLine(line.ToString())
        line.Length = 0 ' Clear buffer

        For i As Integer = 0 To Me.DataGridView1.Rows.Count - 1
            For Each cell As DataGridViewCell In Me.DataGridView1.Rows(i).Cells
                If cell.Value IsNot Nothing Then
                    line.Append(cell.Value.ToString())
                End If

                line.Append(",")
            Next

            line.Length -= 1
            writer.WriteLine(line.ToString())
            line.Length = 0
        Next
    End Using
End Sub

Open in new window

0
 
ITSupermanAuthor Commented:
Thanks for the help!  Your solutions worked very well for what I was needing.
0
 
käµfm³d 👽Commented:
NP. Glad to help  : )
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.