Results 1 to 14 of 14

Thread: Dgv csv

  1. #1

    Thread Starter
    Addicted Member
    Join Date
    Aug 2011
    Posts
    198

    Dgv csv

    Hi all

    I have code to save my DGV in a .txt file:

    Code:
        Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
            Using writer As New StreamWriter("filepath.txt")
                For Each row As DataGridViewRow In Me.DataGridView1.Rows
                    writer.WriteLine(String.Format("{0},{1},{2},{3},{4}", _
                                                   row.Cells(0).Value, _
                                                   row.Cells(1).Value, _
                                                   row.Cells(2).Value, _
                                                   row.Cells(3).Value, _
                                                   row.Cells(4).Value))
                Next
            End Using
    
        End Sub
    How can i reload a Comma Separated Value back into my DGV?

    Many thanks.

    Ps. once I've solved this issue, my programme will be complete!

  2. #2
    Master Of Orion ForumAccount's Avatar
    Join Date
    Jan 2009
    Location
    Canada
    Posts
    2,802

    Re: Dgv csv

    There are a few ways, you can actually use ADO.NET to do this. Your best bet is probably to get the text file into a DataTable object so that you can just bind it to the DataGridView. You could look at the TextFieldParser class to read the fields. While reading the fields, you can add them to a DataTable.

  3. #3

    Thread Starter
    Addicted Member
    Join Date
    Aug 2011
    Posts
    198

    Re: Dgv csv

    Hi there! Thanks for the reply.

    Would it be possible for you to help me with the code for this? I'm not very experienced and so am not great at manipulating vb code. S:

  4. #4
    Master Of Orion ForumAccount's Avatar
    Join Date
    Jan 2009
    Location
    Canada
    Posts
    2,802

    Re: Dgv csv

    This is your project so you should at least try. Start by taking a look at the example in the link that I posted. Get your application to read your file, after you can read your file successfully, start looking at how you could put that in a DataTable.

  5. #5

    Thread Starter
    Addicted Member
    Join Date
    Aug 2011
    Posts
    198

    Re: Dgv csv

    :S I'm sorry to come back with little result..I simply cannot master this at all. I'd really appreciate your help on this one

  6. #6
    Karen Payne MVP kareninstructor's Avatar
    Join Date
    Jun 2008
    Location
    Oregon
    Posts
    6,713

    Re: Dgv csv

    Quote Originally Posted by MacShand View Post
    :S I'm sorry to come back with little result..I simply cannot master this at all. I'd really appreciate your help on this one
    Hello, please show us what you have tried and what was the result.

  7. #7

    Thread Starter
    Addicted Member
    Join Date
    Aug 2011
    Posts
    198

    Re: Dgv csv

    Hi Kevin!

    I tried the following, from the link posted above...

    Code:
    Using MyReader As New Microsoft.VisualBasic.FileIO.
        TextFieldParser("c:\temp\test2")
    
        MyReader.TextFieldType = 
            Microsoft.VisualBasic.FileIO.FieldType.Delimited
        MyReader.Delimiters = New String() {vbTab}
        Dim currentRow As String()
        'Loop through all of the fields in the file. 
        'If any lines are corrupt, report an error and continue parsing. 
        While Not MyReader.EndOfData
            Try
                currentRow = MyReader.ReadFields()
                ' Include code here to handle the row.
            Catch ex As Microsoft.VisualBasic.FileIO.MalformedLineException
                MsgBox("Line " & ex.Message & 
                " is invalid.  Skipping")
            End Try
        End While
    End Using
    However, I'm not sure how to manipulate this into reading my file let alone separating the CSV file into the appropriate fields on my DGV.

    Sorry for the inconvenience...i really do appreciate help!

  8. #8
    Karen Payne MVP kareninstructor's Avatar
    Join Date
    Jun 2008
    Location
    Oregon
    Posts
    6,713

    Re: Dgv csv

    Quote Originally Posted by MacShand View Post
    Hi Kevin!

    I tried the following, from the link posted above...

    Code:
    Using MyReader As New Microsoft.VisualBasic.FileIO.
        TextFieldParser("c:\temp\test2")
    
        MyReader.TextFieldType = 
            Microsoft.VisualBasic.FileIO.FieldType.Delimited
        MyReader.Delimiters = New String() {vbTab}
        Dim currentRow As String()
        'Loop through all of the fields in the file. 
        'If any lines are corrupt, report an error and continue parsing. 
        While Not MyReader.EndOfData
            Try
                currentRow = MyReader.ReadFields()
                ' Include code here to handle the row.
            Catch ex As Microsoft.VisualBasic.FileIO.MalformedLineException
                MsgBox("Line " & ex.Message & 
                " is invalid.  Skipping")
            End Try
        End While
    End Using
    However, I'm not sure how to manipulate this into reading my file let alone separating the CSV file into the appropriate fields on my DGV.

    Sorry for the inconvenience...i really do appreciate help!
    Please take the time and download a sample project ready to go where a file is read in using TextFieldParser where the text file is delimited by tab. There is much more than you need in the sample project, study it and steal from the code as needed.

    http://kevininstructor.home.comcast....ieldParser.zip

  9. #9

    Thread Starter
    Addicted Member
    Join Date
    Aug 2011
    Posts
    198

    Re: Dgv csv

    Hi Kevin

    Thanks for being so willing to share the project and code.

    I can only apologise...but I've spent the evening trying to pick the bits of code that are needed to make my application work and I cannot work out which parts I need.

    I feel this is something that should be relatively straightforward but I just cannot crack it. The only light at the end of the tunnel is that when I do get it, I'll be finished my programme!

    Would you be willing to advise on the code that I specifically need?

    Many thanks for all your time and help.

  10. #10
    Karen Payne MVP kareninstructor's Avatar
    Join Date
    Jun 2008
    Location
    Oregon
    Posts
    6,713

    Re: Dgv csv

    Quote Originally Posted by MacShand View Post
    Hi Kevin

    Thanks for being so willing to share the project and code.

    I can only apologise...but I've spent the evening trying to pick the bits of code that are needed to make my application work and I cannot work out which parts I need.

    I feel this is something that should be relatively straightforward but I just cannot crack it. The only light at the end of the tunnel is that when I do get it, I'll be finished my programme!

    Would you be willing to advise on the code that I specifically need?

    Many thanks for all your time and help.
    Let me drum up another idea for you using TextFieldParser, hang loose.

  11. #11
    Karen Payne MVP kareninstructor's Avatar
    Join Date
    Jun 2008
    Location
    Oregon
    Posts
    6,713

    Re: Dgv csv

    The following for this demo is a file named Products.txt stored in the same folder as your project executable. If you want it some place else than adjust the code.

    The demo is hard coded to work with a three column per line text file. If you have a different amount of columns then you need to adjust the red code below. For each item shown in red there must be a column in the DataGridView for the column. So your DataGridView in this case requires three columns. If there are less columns then a message box appears indicating this. If you have more columns then you need to adjust the code in green. If the file is not present then a message box indicates this. Any other errors are also reported back to you. In a real app you would handle the errors differently of course as the user does not need to see these messages.

    Hope this helps.

    Code:
    1,Chai,boxes x 20 bags,$18.00
    2,Chang,24 - 12 oz bottles,$19.00
    3,Aniseed Syrup,12 - 550 ml bottles,$10.00
    4,Chef Anton's Cajun Seasoning,48 - 6 oz jars,$22.00
    5,Chef Anton's Gumbo Mix36 boxes,$21.35
    6,Grandma's Boysenberry Spread,12 - 8 oz jars,$25.00
    7,Uncle Bob's Organic Dried Pears,12 - 1 lb pkgs.,$30.00
    8,Northwoods Cranberry Sauce,12 - 12 oz jars,$40.00
    9,Mishi Kobe Niku,18 - 500 g pkgs.,$97.00
    10,Ikura,12 - 200 ml jars,$31.00
    Form code
    Code:
    Public Class Form1
       Private ErrorList As New List(Of String)
       Private Sub Form1_Load( _
          ByVal sender As System.Object, _
          ByVal e As System.EventArgs) Handles MyBase.Load
    
          DataGridView1.AllowUserToAddRows = False
    
          If Not DataGridView1.LoadTextFile("Products.txt", ErrorList) Then
             Dim sb As New System.Text.StringBuilder
             sb.AppendLine("Failed to load text file, see error messages below.")
             For Each item In ErrorList
                sb.AppendLine(item)
             Next
             MessageBox.Show(sb.ToString)
          End If
       End Sub
    End Class
    Create Module1.vb in your project with the following code.
    Code:
    Imports Microsoft.VisualBasic.FileIO
    Module Module1
       <System.Diagnostics.DebuggerStepThrough()> _
       <System.Runtime.CompilerServices.Extension()> _
       Public Function LoadTextFile( _
          ByVal sender As DataGridView, _
          ByVal FileName As String, _
          ByRef Errors As List(Of String)) As Boolean
    
          If Not IO.File.Exists(FileName) Then
             Errors.Add("Failed to locate '" & FileName & "'")
             Return False
          End If
    
          If sender.ColumnCount <> 3 Then
    
             Errors.Add("Must have three columns to load your text file., there are " & _
                        sender.ColumnCount.ToString & " columns presently.")
    
             Return False
    
          End If
    
          Using MyReader As New TextFieldParser(FileName)
             MyReader.TextFieldType = FileIO.FieldType.Delimited
             MyReader.Delimiters = New String() {","}
             Dim Line As String()
    
             sender.SuspendLayout()
    
             Try
                While Not MyReader.EndOfData
                   Try
                      Line = MyReader.ReadFields()
                      '
                      ' For every column per line
                      ' there must be a column in the DataGridView
                      '
                      sender.Rows.Add(New Object() {Line(0), Line(1), Line(2)})
                   Catch ex As FileIO.MalformedLineException
                      '
                      ' Report problem
                      '
                      Errors.Add(ex.Message)
                   Catch ex As Exception
                      Errors.Add(ex.Message)
                   End Try
                End While
             Finally
                sender.ResumeLayout()
             End Try
          End Using
    
          Return Errors.Count = 0
    
       End Function
    End Module

  12. #12

    Thread Starter
    Addicted Member
    Join Date
    Aug 2011
    Posts
    198

    Re: Dgv csv

    Kevin, thank you for this. It's absolutely spot on and well outwith my knowledge! it's great to have such helpful experts available! Thank you.

  13. #13
    Karen Payne MVP kareninstructor's Avatar
    Join Date
    Jun 2008
    Location
    Oregon
    Posts
    6,713

    Re: Dgv csv

    Quote Originally Posted by MacShand View Post
    Kevin, thank you for this. It's absolutely spot on and well outwith my knowledge! it's great to have such helpful experts available! Thank you.
    Good to hear this works for you.

  14. #14
    eXtreme Programmer .paul.'s Avatar
    Join Date
    May 2007
    Location
    Chelmsford UK
    Posts
    26,413

    Re: Dgv csv

    as you're using vb2010:

    Quote Originally Posted by kevininstructor View Post
    Code:
    1,Chai,boxes x 20 bags,$18.00
    2,Chang,24 - 12 oz bottles,$19.00
    3,Aniseed Syrup,12 - 550 ml bottles,$10.00
    4,Chef Anton's Cajun Seasoning,48 - 6 oz jars,$22.00
    5,Chef Anton's Gumbo Mix,36 boxes,$21.35
    6,Grandma's Boysenberry Spread,12 - 8 oz jars,$25.00
    7,Uncle Bob's Organic Dried Pears,12 - 1 lb pkgs.,$30.00
    8,Northwoods Cranberry Sauce,12 - 12 oz jars,$40.00
    9,Mishi Kobe Niku,18 - 500 g pkgs.,$97.00
    10,Ikura,12 - 200 ml jars,$31.00


    vb Code:
    1. Public Class Form1
    2.  
    3.     Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
    4.         Dim lines() As String = IO.File.ReadAllLines("csv.txt")
    5.         Dim dt As New DataTable
    6.         dt.Columns.AddRange(New DataColumn() {New DataColumn("id"), New DataColumn("name"), New DataColumn("quantity"), New DataColumn("price")})
    7.         Array.ForEach(lines, Sub(line) dt.Rows.Add(line.Split(","c)))
    8.         datagridview1.datasource = dt
    9.     End Sub
    10.  
    11. End Class

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width