Following examples found on the web and even in stackoverflow I filled in the btnGerarCSV
button that way.
Protected Sub btnGerarCSV_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnGerarCSV.Click
Dim sb As New StringBuilder
Dim gv As New GridView
Try
Page.Response.Clear()
Page.Response.Buffer = True
Page.Response.AddHeader("content-disposition", "attachment;Pedido_" & Session("ddlPedido") & ".csv")
Page.Response.Charset = ""
Page.Response.ContentType = "application/vnd.ms-excel"
grdPedido.DataSource = Session("dtPedidosColetados")
For i As Integer = 0 To grdPedido.Columns.Count - 1
'Adiciona separador por vírgula
sb.Append(grdPedido.Columns(i).HeaderText + ","c)
Next
'Adiciona nova linha
sb.Append(vbCr & vbLf)
For i As Integer = 0 To grdPedido.Rows.Count - 1
For j As Integer = 0 To grdPedido.Columns.Count - 1
'Adiciona separador por vírgula
sb.Append(grdPedido.Rows(i).Cells(j).Text + ","c)
Next
'Adiciona nova linha
sb.Append(vbCr & vbLf)
Next
Response.Output.Write(sb.ToString())
Response.Flush()
Response.End()
Catch ef As ThreadAbortException
Exit Try
Catch ex As Exception
End Try
End Sub
My page works as follows: The user chooses Start Date and End Date and selects the search button. Then grdPedido
is populated and displayed on screen. After that two buttons are displayed, one to export to excel in worksheet, which is working correctly and a button for CSV.
But what happens to me is that on arriving at the line For i As Integer = 0 To grdPedido.Columns.Count - 1
the number of columns is = 0, even the grid returning the query normally.
I've changed the code in several ways, but it always falls into the same problem.