0

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?

Oumie
  • 49
  • 1
  • 5
  • 11
  • Are you *sure* that `gvReports` is populated at the time the handler runs? – Andrew Morton Jan 02 '14 at 20:11
  • @Andrew Yes it is. Looks like binding the gridview again (gvReports.databind()) makes the rowcount zero. I commented it out and it works! Thanks! – Oumie Jan 02 '14 at 20:18

2 Answers2

0

I found the solution!! Comment out

     gvReports.AllowPaging = False
     gvReports.DataBind()
Oumie
  • 49
  • 1
  • 5
  • 11
-1

in place

gvReports.DataBind() 

call function

me.binddata() 

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

V-rund Puro-hit
  • 5,518
  • 9
  • 31
  • 50