Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people, just like you, are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
Solved

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

Posted on 2011-03-20
9
2,590 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
Master Your Team's Linux and Cloud Stack!

The average business loses $13.5M per year to ineffective training (per 1,000 employees). Keep ahead of the competition and combine in-person quality with online cost and flexibility by training with Linux Academy.

 
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
 
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

Announcing the Most Valuable Experts of 2016

MVEs are more concerned with the satisfaction of those they help than with the considerable points they can earn. They are the types of people you feel privileged to call colleagues. Join us in honoring this amazing group of Experts.

Question has a verified solution.

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

The object model of .Net can be overwhelming at times – so overwhelming that quite trivial tasks often take hours of research. In this case, the task at hand was to populate the datagrid from SQL Server database in Visual Studio 2008 Windows applica…
In my previous two articles we discussed Binary Serialization (http://www.experts-exchange.com/A_4362.html) and XML Serialization (http://www.experts-exchange.com/A_4425.html). In this article we will try to know more about SOAP (Simple Object Acces…

809 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