views:

89

answers:

1

I am trying to export a datagrid to a an excel file. It converts the asp:BoundColumn correctly but the template columns with a linkbutton or an imagebutton cannot be converted. Those cells are converted as an empty cell.

Here is the code that exports the controls to excel.,

Public Shared Sub Export(ByVal Mime As String, ByVal Filename As String, ByVal Response As HttpResponse, ByVal Control As Control)

    Dim stringWrite As New System.IO.StringWriter()
    Dim htmlWrite As New System.Web.UI.HtmlTextWriter(stringWrite)
    Response.Clear()
    Response.Buffer = True
    Response.Charset = String.Empty
    Response.ContentType = Mime
    Response.AddHeader("Content-Disposition", "filename=" & Filename)
    Control.RenderControl(htmlWrite)
    Response.Write("<!DOCTYPE html PUBLIC ""-//W3C//DTD XHTML 1.0 Transitional//EN"" ""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd""&gt;&lt;html xmlns=""http://www.w3.org/1999/xhtml""&gt;&lt;head id=""Head1"" runat=""server""><meta http-equiv=""content-type"" content=""text-html; charset=utf-8""></head><body>" & stringWrite.ToString & "</body></html>")
    Response.End()
End Sub

Where the problem could be? Any ideas? Thanks in advance.

+1  A: 

Basically the problem is with rendering non-literal controls outside of a server-side form.

Here are a couple of articles that are focused on doing this with a GridView, but should work okay with a DataGrid as well. The main thing to look at is the function they call before rendering the grid that goes through the controls in the grid and converts any LinkButtons, etc. into literals.

Article 1: A simpler, more "hard-coded" way, specifically for LinkButtons and Dropdownlists (look towards the bottom for the DisableControls function)

Article 2: A more robust and flexible method to deal with different types of controls

patmortech