#Region "GridView Export"
Public Sub ExportGridView(ByVal gridview As GridView)
PrepareGridViewForExport(gridview)
RenderGridView(gridview)
End Sub
Private Sub RenderGridView(ByVal gridview As GridView)
Dim allowSorting As Boolean = gridview.AllowSorting
gridview.AllowSorting = False
Dim attachment As String = "attachment; filename=Export.xls"
Page.Response.ClearContent()
Page.Response.AddHeader("content-disposition", attachment)
Page.Response.ContentType = "application/ms-excel"
Dim sw As IO.StringWriter = New IO.StringWriter
Dim htw As HtmlTextWriter = New HtmlTextWriter(sw)
Dim frm As HtmlForm = New HtmlForm()
gridview.Parent.Controls.Add(frm)
frm.Attributes("runat") = "server"
frm.Controls.Add(gridview)
frm.RenderControl(htw)
Page.Response.Write(sw.ToString)
Page.Response.End()
gridview.AllowSorting = allowSorting
End Sub
Private Sub PrepareGridViewForExport(ByVal gv As Control)
Dim lb As LinkButton = New LinkButton
Dim l As Literal = New Literal
Dim name As String = String.Empty
Dim i As Integer = 0
Do While (i < gv.Controls.Count)
If (gv.Controls(i).GetType Is GetType(LinkButton)) Or (gv.Controls(i).GetType Is GetType(HyperLink)) Or (gv.Controls(i).GetType Is GetType(HyperLinkField)) Then
l.Text = CType(gv.Controls(i), LinkButton).Text
gv.Controls.Remove(gv.Controls(i))
gv.Controls.AddAt(i, l)
ElseIf (gv.Controls(i).GetType Is GetType(DropDownList)) Then
l.Text = CType(gv.Controls(i), DropDownList).SelectedItem.Text
gv.Controls.Remove(gv.Controls(i))
gv.Controls.AddAt(i, l)
ElseIf (gv.Controls(i).GetType Is GetType(CheckBox)) Then
l.Text = CType(gv.Controls(i), CheckBox).Checked
gv.Controls.Remove(gv.Controls(i))
gv.Controls.AddAt(i, l)
End If
If gv.Controls(i).HasControls Then
PrepareGridViewForExport(gv.Controls(i))
End If
i += 1
Loop
End Sub
#End Region