Solved

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

Posted on 2011-03-20
9
2,521 Views
Last Modified: 2013-12-17
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.
0
Comment
Question by:ITSuperman
  • 4
  • 4
9 Comments
 
LVL 17

Expert Comment

by:nepaluz
ID: 35176332
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
 
LVL 3

Author Comment

by:ITSuperman
ID: 35176375
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
 
LVL 75

Accepted Solution

by:
käµfm³d   👽 earned 500 total points
ID: 35176629
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
 
LVL 3

Author Comment

by:ITSuperman
ID: 35176850
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
3 Use Cases for Connected Systems

Our Dev teams are like yours. They’re continually cranking out code for new features/bugs fixes, testing, deploying, testing some more, responding to production monitoring events and more. It’s complex. So, we thought you’d like to see what’s working for us.

 
LVL 75

Assisted Solution

by:käµfm³d 👽
käµfm³d   👽 earned 500 total points
ID: 35176974
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
 
LVL 3

Author Comment

by:ITSuperman
ID: 35177041
Looks great!  I will be testing this tonight and will give you full points on it.  
0
 
LVL 75

Assisted Solution

by:käµfm³d 👽
käµfm³d   👽 earned 500 total points
ID: 35177551
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
 
LVL 3

Author Closing Comment

by:ITSuperman
ID: 35181973
Thanks for the help!  Your solutions worked very well for what I was needing.
0
 
LVL 75

Expert Comment

by:käµfm³d 👽
ID: 35182509
NP. Glad to help  : )
0

Featured Post

3 Use Cases for Connected Systems

Our Dev teams are like yours. They’re continually cranking out code for new features/bugs fixes, testing, deploying, testing some more, responding to production monitoring events and more. It’s complex. So, we thought you’d like to see what’s working for us.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Summary Displaying images in RichTextBox is a common requirement with limited solutions available. Pasting through clipboard or embedding into RTF content only support static images.  This article describes how to insert Windows control objects int…
In my previous article (http://www.experts-exchange.com/Programming/Languages/.NET/.NET_Framework_3.x/A_4362-Serialization-in-NET-1.html) we saw the basics of serialization and how types/objects can be serialized to Binary format. In this blog we wi…
Get a first impression of how PRTG looks and learn how it works.   This video is a short introduction to PRTG, as an initial overview or as a quick start for new PRTG users.
This tutorial demonstrates a quick way of adding group price to multiple Magento products.

914 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

12 Experts available now in Live!

Get 1:1 Help Now