Saturday, November 24, 2007

Exporting Gridview to Excel - With Checkbox

I often get the same questions asked of my while working with 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" >
<asp:TemplateField><ItemTemplate><asp:CheckBox ID="cbSelect" runat="server" /></ItemTemplate></asp:TemplateField>
<asp:BoundField DataField="id" />
<asp:BoundField DataField="member" />

<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/"

'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
counter = 0
End If
End If


'Write the HTML to the browser

'End the response

End Sub

No comments: