Saturday, November 24, 2007

Exporting Gridview to Excel - With Checkbox

I often get the same questions asked of my while working with asp.net. If these examples seem to simplistic then please move along :)

Exporting a gridview to excel is pretty simple, there are plently of examples on the net, however not to many when it comes to only selecting certain rows to export.

an example Gridview and button


<asp:GridView ID="dg_disp" runat="server" AutoGenerateColumns="False" DataKeyNames="id" DataSourceID="SqlDataSource1" >
<Columns>
<asp:TemplateField><ItemTemplate><asp:CheckBox ID="cbSelect" runat="server" /></ItemTemplate></asp:TemplateField>
<asp:BoundField DataField="id" />
<asp:BoundField DataField="member" />
</Columns>
</asp:GridView>

<asp:button id="Button1" runat="server" />

---Code Behind---



Private Sub button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles button1.Click

' Set the content type to Excel
Response.ContentType = "application/vnd.ms-excel"

'Turn off the view state
Me.EnableViewState = False

'Remove the charset from the Content-Type header
Response.Charset = String.Empty

Dim myTextWriter As New System.IO.StringWriter()
Dim myHtmlTextWriter As New System.Web.UI.HtmlTextWriter(myTextWriter)
Dim colCount As Integer = dg_disp.Columns.Count
Dim counter As Integer = 0

'loop through all rows in the gridview
For Each row As GridViewRow In dg_disp.Rows

'skip header footers rows etc
If row.RowType = DataControlRowType.DataRow Then

'find the checkbox in the template field
Dim i As CheckBox = row.FindControl("cbSelect")

If i.Checked = True Then
While counter <> colCount

'don't output checkbox field change if checkbox is in different place
If counter <> 0 Then
Response.Write(row.Cells(counter).Text & vbTab)
End If

counter = counter + 1
End While
Response.Write(vbCr)
counter = 0
End If
End If

Next


'Write the HTML to the browser
Response.Write(myTextWriter.ToString())

'End the response
Response.End()

End Sub




No comments: