Solved

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

Posted on 2011-03-20
9
2,495 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
Comment Utility
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
Comment Utility
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 74

Accepted Solution

by:
käµfm³d   👽 earned 500 total points
Comment Utility
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
Comment Utility
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
What Should I Do With This Threat Intelligence?

Are you wondering if you actually need threat intelligence? The answer is yes. We explain the basics for creating useful threat intelligence.

 
LVL 74

Assisted Solution

by:käµfm³d 👽
käµfm³d   👽 earned 500 total points
Comment Utility
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
Comment Utility
Looks great!  I will be testing this tonight and will give you full points on it.  
0
 
LVL 74

Assisted Solution

by:käµfm³d 👽
käµfm³d   👽 earned 500 total points
Comment Utility
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
Comment Utility
Thanks for the help!  Your solutions worked very well for what I was needing.
0
 
LVL 74

Expert Comment

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

Featured Post

Find Ransomware Secrets With All-Source Analysis

Ransomware has become a major concern for organizations; its prevalence has grown due to past successes achieved by threat actors. While each ransomware variant is different, we’ve seen some common tactics and trends used among the authors of the malware.

Join & Write a Comment

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…
Real-time is more about the business, not the technology. In day-to-day life, to make real-time decisions like buying or investing, business needs the latest information(e.g. Gold Rate/Stock Rate). Unlike traditional days, you need not wait for a fe…
Here's a very brief overview of the methods PRTG Network Monitor (https://www.paessler.com/prtg) offers for monitoring bandwidth, to help you decide which methods you´d like to investigate in more detail.  The methods are covered in more detail in o…
This video shows how to remove a single email address from the Outlook 2010 Auto Suggestion memory. NOTE: For Outlook 2016 and 2013 perform the exact same steps. Open a new email: Click the New email button in Outlook. Start typing the address: …

771 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

10 Experts available now in Live!

Get 1:1 Help Now