Results 1 to 12 of 12

Thread: update .csv file from gridview

  1. #1

    Thread Starter
    New Member
    Join Date
    Jun 2016
    Posts
    6

    update .csv file from gridview

    Hi. I am trying to read a .csv-file into a gridview, insert record, update record and delete records. So far I have managed to read the csv file into the gridview but inserting, updating and deleting records is not working for me, and I hope somebody can help. My aspx-file is like this:


    Code:
        <asp:Panel ID="editPanel" runat="server" CssClass="margin-bottom-40" Visible="false">
    
            <div id="dvGrid">
    
                <asp:UpdatePanel ID="UpdatePanel1" runat="server">
                    <ContentTemplate>
                       
                        <asp:GridView ID="GridView1" 
                            runat="server"
                            CellPadding="6"
                            AutoGenerateColumns="false" 
                            DataKeyNames="animalID"
                            AlternatingRowStyle-BackColor="#f7f7f7"
                            HeaderStyle-BackColor="#dadada"
                            AllowSorting="true"
                            RowStyle-HorizontalAlign="right"
                            ShowFooter="true"  
                            OnPageIndexChanging="OnPaging" 
                            OnRowEditing="OnRowEditing"
                            OnRowUpdating="OnRowUpdating" 
                            OnRowCancelingEdit="OnRowCancelingEdit"
                            OnRowDeleting="OnRowDeleting"
                            EmptyDataText="No records has been added."
                            PageSize="10"
                            EnableSortingAndPagingCallbacks="true">
                            
                        <Columns>
    
                            <asp:CommandField ButtonType="Link" ShowEditButton="True" />
    
                            <asp:TemplateField HeaderText="Cow No." SortExpression="animalID">
                                <ItemTemplate>
                                    <asp:Label ID="lblanimalID" runat="server" Text='<%# Eval("animalID")%>'></asp:Label>
                                </ItemTemplate> 
                                <FooterTemplate>
                                    <asp:TextBox ID="txtanimalID" MaxLength="12" runat="server" CssClass="input_wide"></asp:TextBox>
                                </FooterTemplate> 
                            </asp:TemplateField> 
    
                            <asp:TemplateField HeaderText="Gram / day 1" SortExpression="24hoursallowancesup1">
                                <ItemTemplate>
                                    <asp:Label ID="lbl24hoursallowancesup1" runat="server" Text='<%# Eval("24hoursallowancesup1")%>'></asp:Label>
                                </ItemTemplate>
                                <EditItemTemplate>
                                    <asp:TextBox ID="txt24hoursallowancesup1" runat="server" Text='<%# Eval("24hoursallowancesup1")%>' CssClass="input_narrow"></asp:TextBox>
                                </EditItemTemplate>  
                                <FooterTemplate>
                                    <asp:TextBox ID="txt24hoursallowancesup1" runat="server" CssClass="input_narrow"></asp:TextBox>
                                </FooterTemplate> 
                            </asp:TemplateField>
    
                            <asp:TemplateField HeaderText="Gram / day 2" SortExpression="24hoursallowancesup2">
                                <ItemTemplate>
                                    <asp:Label ID="lbl24hoursallowancesup2" runat="server" Text='<%# Eval("24hoursallowancesup2")%>'></asp:Label>
                                </ItemTemplate>
                                <EditItemTemplate>
                                    <asp:TextBox ID="txt24hoursallowancesup2" runat="server" Text='<%# Eval("24hoursallowancesup2")%>' CssClass="input_narrow"></asp:TextBox>
                                </EditItemTemplate>  
                                <FooterTemplate>
                                    <asp:TextBox ID="txt24hoursallowancesup2" runat="server" CssClass="input_narrow"></asp:TextBox>
                                </FooterTemplate> 
                            </asp:TemplateField>
    
                            <asp:TemplateField HeaderText="Rest 1" SortExpression="accumulatedallowancesup1">
                                <ItemTemplate>
                                    <asp:Label ID="lblaccumulatedallowancesup1" runat="server" Text='<%# Eval("accumulatedallowancesup1")%>'></asp:Label>
                                </ItemTemplate> 
                            </asp:TemplateField> 
    
                            <asp:TemplateField HeaderText="Rest 2" SortExpression="accumulatedallowancesup2">
                                <ItemTemplate>
                                    <asp:Label ID="lblaccumulatedallowancesup2" runat="server" Text='<%# Eval("accumulatedallowancesup2")%>'></asp:Label>
                                </ItemTemplate> 
                            </asp:TemplateField> 
    
                            <asp:TemplateField HeaderText="Visits 1" SortExpression="successfullvisits1">
                                <ItemTemplate>
                                    <asp:Label ID="lblsuccessfullvisits1" runat="server" Text='<%# Eval("successfullvisits1")%>'></asp:Label>
                                </ItemTemplate> 
                            </asp:TemplateField> 
    
                            <asp:TemplateField HeaderText="Visits 2" SortExpression="successfullvisits2">
                                <ItemTemplate>
                                    <asp:Label ID="lblsuccessfullvisits2" runat="server" Text='<%# Eval("successfullvisits2")%>'></asp:Label>
                                </ItemTemplate> 
                            </asp:TemplateField> 
    
                            <asp:TemplateField HeaderText="Delete">
                                <ItemTemplate>
                                    <asp:LinkButton ID="OnRowDeleting" runat="server" CommandArgument='<%# Eval("animalID")%>' OnClientClick="return confirm('Do you want to delete?')" Text="&#xf00d;" CssClass="fa fa-2x color-red nobtn"></asp:LinkButton>
                                </ItemTemplate>
                                <FooterTemplate>
                                    <asp:LinkButton ID="OnRowAdding" runat="server" Text="&#xf0c7;" CssClass="fa fa-2x color-green nobtn align_right"></asp:LinkButton>
                                </FooterTemplate> 
    
                            </asp:TemplateField> 
                            
                        </Columns> 
    
                    </asp:GridView> 
    
                </ContentTemplate> 
    
                <Triggers>
                    <asp:AsyncPostBackTrigger ControlID = "GridView1" /> 
                </Triggers> 
    
            </asp:UpdatePanel> 
        </div>
             
        </asp:Panel>

    My code-behind is:

    Code:
    Imports System.Data.OleDb
    Imports System.IO
    Imports System.Data.SqlClient
    Imports Microsoft.VisualBasic.FileIO
    
    Public Class pitstop1
        Inherits System.Web.UI.Page
    
        Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
    
            If Page.IsPostBack = False Then
                If Session("MemberAccessLevel") >= 4 Then
    
                    'We get the herd number
    
                    Try
                        Dim Secondaryconnection As String = ConfigurationManager.ConnectionStrings("SecondaryConnection").ToString()
                        Dim sql As String = "SELECT members.herd_number, herd_name FROM members WHERE members.MemberIndex = " & Session("MemberIndex") & ""
                        Dim cn As New OleDbConnection(Secondaryconnection),
                    cmd As New OleDbCommand(sql, cn)
                        cn.Open()
                        Dim reader As OleDbDataReader = cmd.ExecuteReader
                        While reader.Read()
                            herd_number.Text = reader("herd_number")
                            herd_name.Text = reader("herd_name")
                            If herd_number.Text > "0" Then
                                menu.Visible = True
                            Else
                                Response.Redirect("/account/login.aspx?status=not_pitstop&rUrl=/")
                            End If
                        End While
    
                    Catch ex As Exception
                        Response.Write(ex.Message)
                    End Try
    
                Else
                    Response.Redirect("/account/login.aspx?status=not_logged_in&rUrl=/pitstop_manager.aspx")
                End If
            End If
    
        End Sub
    
        Protected Sub editBtn_Click(sender As Object, e As EventArgs) Handles editBtn.Click
    
            menu.Visible = False
            editPanel.Visible = True
    
            'If File.Exists("pitstop_herddata/59523B.csv") Then
            If (System.IO.File.Exists(MapPath("pitstop_herddata/59523B.csv"))) Then
    
                BindData()
                table2()
    
            Else
                MsgBox("The file is NOT found.")
            End If
    
        End Sub
    
        Private Sub BindData()
    
            Dim csvPath As String = Server.MapPath("~/pitstop_herddata/") + Path.GetFileName("59523B.csv")
            Dim dta As New DataTable()
    
            dta.Columns.AddRange(New DataColumn(6) {New DataColumn("animalID", GetType(String)), New DataColumn("24hoursallowancesup1", GetType(String)), New DataColumn("24hoursallowancesup2", GetType(String)), New DataColumn("accumulatedallowancesup1", GetType(String)), New DataColumn("accumulatedallowancesup2", GetType(String)), New DataColumn("successfullvisits1", GetType(String)), New DataColumn("successfullvisits2", GetType(String))})
    
            Dim csvData As String = File.ReadAllText(csvPath)
            For Each row As String In csvData.Split(ControlChars.Lf).Skip(1)
                If Not String.IsNullOrEmpty(row) Then
                    dta.Rows.Add()
                    Dim i As Integer = 0
                    For Each cell As String In row.Split(";"c)
                        dta.Rows(dta.Rows.Count - 1)(i) = cell
                        i += 1
                    Next
                End If
            Next
    
            GridView1.DataSource = dta
            GridView1.DataBind()
    
        End Sub
        Protected Sub OnRowEditing(ByVal sender As Object, ByVal e As GridViewEditEventArgs)
    
            GridView1.EditIndex = e.NewEditIndex
            BindData()
    
        End Sub
    
        Protected Sub OnRowCancelingEdit(ByVal sender As Object, ByVal e As GridViewCancelEditEventArgs)
    
            GridView1.EditIndex = -1
            BindData()
    
        End Sub
    
        Protected Sub OnRowUpdating(ByVal sender As Object, ByVal e As GridViewUpdateEventArgs)
    
            'create a new stream(file) writer based on supplied path
            Dim fw As New IO.StreamWriter(Server.MapPath("~/pitstop_herddata/59523B.csv"))
            'write a section for columns collection
            'fw.WriteLine("[column]")
            'For Each column, write the column name within a line
            For x As Integer = 0 To GridView1.Columns.Count - 2
                If x > 0 And x < 8 Then
                    fw.Write(GridView1.Columns.Item(x).HeaderText + ";")
                End If
            Next
            'write a section for rows collection
            fw.WriteLine()
            'row controller
            For y As Integer = 0 To GridView1.Rows.Count - 1
                If y > 0 Then
                    'for each cell, write the cell value followed by a comma
                    For x As Integer = 0 To GridView1.Columns.Count - 1
                        If x > 0 And x < 8 Then
                            fw.Write(GridView1.Rows.Item(y).Cells(x).Text + ";")
                        End If
                    Next
                End If
                'ends the line
                fw.WriteLine(y)
    
            Next
            'close the file writer
            fw.Close()
        End Sub
    
       Protected Sub OnRowDeleting(ByVal sender As Object, ByVal e As EventArgs)
    
        End Sub
    
    
        Protected Sub OnRowAdding(ByVal sender As Object, ByVal e As EventArgs)
    
        End Sub
    
    End Class

    The above code can read and save the column headers into the csv file but not the table data. I have searched for code snippets but none of them are working for me. The .csv file I am using contains the following data:

    animalID 24hoursallowancesup1 24hoursallowancesup2 accumulatedallowancesup1 accumulatedallowancesup2 successfullvisits1 successfullvisits2
    5952300318 120 100 80 120 10 13
    5952301321 100 80 280 60 3 1
    5952301387 140 60 90 40 8 4

    I hope somebody can help.

    /henn
    Last edited by dday9; Jun 15th, 2016 at 10:57 AM.

  2. #2
    Frenzied Member KGComputers's Avatar
    Join Date
    Dec 2005
    Location
    Cebu, PH
    Posts
    2,020

    Re: update .csv file from gridview

    Welcome to the forums.

    Kindly wrap your code snippets with code tags for readability. Since this is an asp.net issue, I'll inform the mods to transfer this to the appropriate
    subforum.

    -kgc
    CodeBank: VB.NET & C#.NET | ASP.NET
    Programming: C# | VB.NET
    Blogs: Personal | Programming
    Projects: GitHub | jsFiddle
    ___________________________________________________________________________________

    Rating someone's post is a way of saying Thanks...

  3. #3
    Frenzied Member KGComputers's Avatar
    Join Date
    Dec 2005
    Location
    Cebu, PH
    Posts
    2,020

    Re: update .csv file from gridview

    And as for the issue,

    I have a CRUD(Create/Update/Delete) sample project in the asp.net codebank using the GridView control and Bootstrap. Maybe some of the functionalities
    there might help you.

    ASP-NET-GridView-CRUD-with-Bootstrap

    - kgc
    CodeBank: VB.NET & C#.NET | ASP.NET
    Programming: C# | VB.NET
    Blogs: Personal | Programming
    Projects: GitHub | jsFiddle
    ___________________________________________________________________________________

    Rating someone's post is a way of saying Thanks...

  4. #4

    Thread Starter
    New Member
    Join Date
    Jun 2016
    Posts
    6

    Re: update .csv file from gridview

    Thanks for your answer, but the situation is that I need to use a comma separated file - a .csv-file - and not a conventional database table. My problem is neither dealing with the styling. I hope somebody could check my code and suggest how I can make it function.




    Quote Originally Posted by KGComputers View Post
    And as for the issue,

    I have a CRUD(Create/Update/Delete) sample project in the asp.net codebank using the GridView control and Bootstrap. Maybe some of the functionalities
    there might help you.

    ASP-NET-GridView-CRUD-with-Bootstrap

    - kgc

  5. #5
    Frenzied Member KGComputers's Avatar
    Join Date
    Dec 2005
    Location
    Cebu, PH
    Posts
    2,020

    Re: update .csv file from gridview

    We do have a windows app C# project before to remove rows and insert new rows in a csv file. No updating of csv values of course. See if I can pull that up from our files. That was like years ago..

    Then maybe incorporate that functionality in an asp.net project.

    - kgc
    CodeBank: VB.NET & C#.NET | ASP.NET
    Programming: C# | VB.NET
    Blogs: Personal | Programming
    Projects: GitHub | jsFiddle
    ___________________________________________________________________________________

    Rating someone's post is a way of saying Thanks...

  6. #6
    VB Addict Pradeep1210's Avatar
    Join Date
    Apr 2004
    Location
    Inside the CPU...
    Posts
    6,614

    Re: update .csv file from gridview

    How big is the CSV File? How many records?
    Pradeep, Microsoft MVP (Visual Basic)
    Please appreciate posts that have helped you by clicking icon on the left of the post.
    "A problem well stated is a problem half solved." — Charles F. Kettering

    Read articles on My Blog101 LINQ SamplesJSON ValidatorXML Schema Validator"How Do I" videos on MSDNVB.NET and C# ComparisonGood Coding PracticesVBForums Reputation SaverString EnumSuper Simple Tetris Game


    (2010-2013)
    NB: I do not answer coding questions via PM. If you want my help, then make a post and PM me it's link. If I can help, trust me I will...

  7. #7

    Thread Starter
    New Member
    Join Date
    Jun 2016
    Posts
    6

    Re: update .csv file from gridview

    I feel I am very close to make it function with my code, and the best for me would be if somebody could tell me why I can alone update the headers and not the record values. Sorry, but I do not see how a C# code could help me. There are numerous code examples on the web in VB.NET, also recent, and it seems I managed to make it close to function.

  8. #8

    Thread Starter
    New Member
    Join Date
    Jun 2016
    Posts
    6

    Re: update .csv file from gridview

    As mentioned, the .csv file I am using contains the following data:

    animalID 24hoursallowancesup1 24hoursallowancesup2 accumulatedallowancesup1 accumulatedallowancesup2 successfullvisits1 successfullvisits2
    5952300318 120 100 80 120 10 13
    5952301321 100 80 280 60 3 1
    5952301387 140 60 90 40 8 4

    Unfortunately, this forum doesn't allow me to upload the file, which is only a test file and in reality there would be up to several hundred records.

  9. #9
    Frenzied Member KGComputers's Avatar
    Join Date
    Dec 2005
    Location
    Cebu, PH
    Posts
    2,020

    Re: update .csv file from gridview

    I feel I am very close to make it function with my code
    How about posting your updated codes. Maybe others could take a look at it.

    - kgc
    CodeBank: VB.NET & C#.NET | ASP.NET
    Programming: C# | VB.NET
    Blogs: Personal | Programming
    Projects: GitHub | jsFiddle
    ___________________________________________________________________________________

    Rating someone's post is a way of saying Thanks...

  10. #10

    Thread Starter
    New Member
    Join Date
    Jun 2016
    Posts
    6

    Re: update .csv file from gridview

    The codes are above - tell me are you joking???? Could you delete my account and the thread. This seems to turn into being a waste of my time.

  11. #11
    VB Addict Pradeep1210's Avatar
    Join Date
    Apr 2004
    Location
    Inside the CPU...
    Posts
    6,614

    Re: update .csv file from gridview

    While reading/writing data from flat file is a bit cumbersome as compared to any database, it is not as hard as it might seem like.

    Modify your code like this.

    1. In your aspx file add a column to the grid to hold a unique record number. We will use this Record Number later to identify the line in the file that we want to update. Ensure that the column is not visible. (I prefer keeping such columns as first or last column in the grid).

    asp.net Code:
    1. <asp:TemplateField HeaderText="RecordID" visible="false">
    2.     <ItemTemplate>
    3.         <asp:Label ID="lblRecordID" runat="server" Text='<%# Eval("RecordID")%>'></asp:Label>
    4.     </ItemTemplate>
    5. </asp:TemplateField>

    2. Change your BindData method and add a column named "RecordID" in the datatable you are binding to the grid. So ultimately your BindData method would look like this:

    vb.net Code:
    1. Private Sub BindData()
    2.     Dim csvPath As String = Server.MapPath("~/pitstop_herddata/") + Path.GetFileName("59523B.csv")
    3.     Dim dta As New DataTable()
    4.  
    5.     dta.Columns.AddRange(New DataColumn() { _
    6.                                             New DataColumn("RecordID", GetType(Integer)), _
    7.                                             New DataColumn("animalID", GetType(String)), _
    8.                                             New DataColumn("24hoursallowancesup1", GetType(String)), _
    9.                                             New DataColumn("24hoursallowancesup2", GetType(String)), _
    10.                                             New DataColumn("accumulatedallowancesup1", GetType(String)), _
    11.                                             New DataColumn("accumulatedallowancesup2", GetType(String)), _
    12.                                             New DataColumn("successfullvisits1", GetType(String)), _
    13.                                             New DataColumn("successfullvisits2", GetType(String))})
    14.  
    15.     Dim csvData() As String = File.ReadAllLines(csvPath)
    16.     For rowNum As Integer = 1 To csvData.Length - 1
    17.         If Not String.IsNullOrWhiteSpace(csvData(rowNum)) Then
    18.             Dim rowData() As String = Split(csvData(rowNum), ";")
    19.             dta.Rows.Add(rowNum, rowData(0), rowData(1), rowData(2), rowData(3), rowData(4), rowData(5), rowData(6))
    20.         End If
    21.     Next
    22.  
    23.     GridView1.DataSource = dta
    24.     GridView1.DataBind()
    25. End Sub

    3. Finally your OnRowUpdating method goes like this. (Read inline for details)
    vb.net Code:
    1. Protected Sub OnRowUpdating(ByVal sender As Object, ByVal e As GridViewUpdateEventArgs)
    2.     '-- read the data from file
    3.     Dim csvPath As String = Server.MapPath("~/pitstop_herddata/") + Path.GetFileName("59523B.csv")
    4.     Dim csvData() As String = File.ReadAllLines(csvPath)
    5.  
    6.     '-- get the record number we are updating and prefill the exiting values in an array
    7.     Dim recordId As Integer = DirectCast(GridView1.Rows(e.RowIndex).FindControl("lblRecordID"), Label).Text
    8.     Dim newRowData() As String = Split(csvData(recordId), ";")
    9.  
    10.     '-- fill updated values from Grid
    11.     'newRowData(0) = DirectCast(GridView1.Rows(e.RowIndex).FindControl("txtanimalID"), TextBox).Text
    12.     newRowData(1) = DirectCast(GridView1.Rows(e.RowIndex).FindControl("txt24hoursallowancesup1"), TextBox).Text
    13.     newRowData(2) = DirectCast(GridView1.Rows(e.RowIndex).FindControl("txt24hoursallowancesup2"), TextBox).Text
    14.  
    15.     '-- write back the updated data to file
    16.     csvData(recordId) = Join(newRowData, ";")
    17.     IO.File.WriteAllLines(csvPath, csvData)
    18.  
    19.     '-- refresh the grid
    20.     GridView1.EditIndex = -1
    21.     BindData()
    22. End Sub

    The above should work. However, the code is not optimized and I would leave that part to you.
    Last edited by Pradeep1210; Jun 17th, 2016 at 02:20 PM.
    Pradeep, Microsoft MVP (Visual Basic)
    Please appreciate posts that have helped you by clicking icon on the left of the post.
    "A problem well stated is a problem half solved." — Charles F. Kettering

    Read articles on My Blog101 LINQ SamplesJSON ValidatorXML Schema Validator"How Do I" videos on MSDNVB.NET and C# ComparisonGood Coding PracticesVBForums Reputation SaverString EnumSuper Simple Tetris Game


    (2010-2013)
    NB: I do not answer coding questions via PM. If you want my help, then make a post and PM me it's link. If I can help, trust me I will...

  12. #12

    Thread Starter
    New Member
    Join Date
    Jun 2016
    Posts
    6

    Re: update .csv file from gridview

    Thanks a lot Pradeep1210 - it is working now .

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