title: How can I build a CSV file from a GridView in Visual Basic?
body: <p>I have a report I'm generating in VB.Net that is being displayed in a GridView. The data is pulled from SQL based on some constraints the user enters and can be any size, depending on these. I would like to be able to take these values from the grid and put them into a CSV for a downloadable report without rerunning my SQL select (I know how to build one that way), preferably in a generic fashion so this can be easily reused.
  Here's what I have currently. It makes a CSV, but only the headers are present.</p>
  
  <pre><code>Protected Sub btnExcel_Click(sender As Object, e As EventArgs) Handles btnExcel.Click
      Dim strOutput As New StringBuilder
  
      Response.ContentType = "application/csv"
      ' Remove the charset from the Content-Type header.
      Response.Charset = ""
      ' Turn off the view state.
      Me.EnableViewState = False
      Response.AddHeader("Content-Disposition", "filename=report.csv;")
  
      strOutput.AppendLine(GetCSVLine(grid.HeaderRow.Cells))
      For Each row As GridViewRow In grid.Rows
          strOutput.AppendLine(GetCSVLine(row.Cells))
      Next
  
  
      Response.Write(strOutput)
  
      Response.Flush()
  
      Response.End()
  End Sub
  
  Private Function GetCSVLine(cells As TableCellCollection) As String
      Dim returnValue As String = ""
  
      For Each cell As TableCell In cells
          returnValue += cell.Text + ","
      Next
  
      Return returnValue
  End Function
  </code></pre>
  
  <p>And the aspx page</p>
  
  <pre><code>    &lt;asp:GridView ID="grid" runat="server" EnableModelValidation="True" AutoGenerateColumns = "false"&gt;
                      &lt;Columns&gt;
                          &lt;asp:TemplateField HeaderText="Name"&gt;
                              &lt;ItemTemplate&gt;
                                  &lt;asp:Label ID="lblName" runat="server" Text='&lt;%# Bind("Name")%&gt;'/&gt;&amp;nbsp;
                              &lt;/ItemTemplate&gt;
                          &lt;/asp:TemplateField&gt;
                          &lt;asp:TemplateField HeaderText="Location"&gt;
                              &lt;ItemTemplate&gt;
                                  &lt;asp:Label ID="lblLocation" runat="server" Text='&lt;%# Bind("Location")%&gt;'/&gt;&amp;nbsp;
                              &lt;/ItemTemplate&gt;
                          &lt;/asp:TemplateField&gt;
  &lt;!-- There are a few more fields after this, using the same structure --&gt;
  </code></pre>