Trying to export asp.net gridview to a .csv file

I am trying to export a gridview to a csv file but my code seems to be only exporting the header.

Here is my code:

Protected Sub btnCSV_Click(sender As Object, e As EventArgs) Handles btnCSV.Click
    Response.Clear()
    Response.Buffer = True
    Response.AddHeader("content-disposition", "attachment;filename=GridViewExport.csv")
    Response.Charset = ""
    Response.ContentType = "application/text"

    gvReports.AllowPaging = False
    gvReports.DataBind()

    Dim sb As New StringBuilder()
    For k As Integer = 0 To gvReports.Columns.Count - 1
        'add separator
        sb.Append(gvReports.Columns(k).HeaderText + ","c)
    Next
    'append new line
    sb.Append(vbCr & vbLf)
    For i As Integer = 0 To gvReports.Rows.Count - 1
        For k As Integer = 0 To gvReports.Columns.Count - 1
            'add separator
            sb.Append(gvReports.Rows(i).Cells(k).Text + ","c)
        Next
        'append new line
        sb.Append(vbCr & vbLf)
    Next
    Response.Output.Write(sb.ToString())
    Response.Flush()
    Response.End()
End Sub

After I click the Export to CSV button, I only get one line of data (i.e- the header rows of the gridview). What am I doing wrong here?

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

I found the solution!! Comment out

     gvReports.AllowPaging = False
     gvReports.DataBind()

Method 2

in place

gvReports.DataBind()

call function

me.binddata()

that can load data to gridview.
binddata is the function name


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x