Results 1 to 2 of 2

Thread: Exporting GridView as Word File

  1. #1

    Thread Starter
    Hyperactive Member
    Join Date
    Jul 2007
    Posts
    502

    Exporting GridView as Word File

    I found a site which indicates they can export a GridView as Word, Excel, PDF, and CSV. The PDF uses an external library (iTEXT), and I have not tested that. (http://www.aspsnippets.com/Articles/...n-ASP.Net.aspx)

    The CSV worked for me as specified. But I am having trouble with the Word and Excel portions. The code for the Word sub is

    Code:
     Protected Sub btnExportToWord_Click(sender As Object, e As EventArgs) Handles btnExportToWord.Click
            Dim s As String
    
            Response.Clear()
            Response.Buffer = True
            Response.AddHeader("content-disposition", "attachment;filename=GridViewExport.doc")
            Response.Charset = ""
            Response.ContentType = "application/vnd.ms-word "
            Dim sw As New StringWriter()
            Dim hw As New HtmlTextWriter(sw)
            Try
                GridView1.AllowPaging = False
                GridView1.DataBind()
                GridView1.RenderControl(hw)       ' <<<<<< triggers error
                Response.Output.Write(sw.ToString())
                Response.Flush()
                Response.End()
            Catch ex As Exception
                s = ex.Message
            End Try
        End Sub
    The marked line above triggers an error which states

    Code:
    Control 'MainContent_GridView1' of type 'GridView' must be placed inside a form tag with runat=server.
    Note, that the code never gets the Response.Output.Write line, but the file is downloaded, and looks correct.

    My real need is to download the excel file, but it has the some behaviour. It fails at a similar RenderControl statement, but does download the file, although Excel indicates it is in a non-standard format (but looks fine when opened. I can upload that code too, but the Word one above is simpler.

    Any ideas what is going on and how to fix these issues?

  2. #2

    Thread Starter
    Hyperactive Member
    Join Date
    Jul 2007
    Posts
    502

    Re: Exporting GridView as Word File

    I found similar errors on the web. They suggest adding

    Code:
       Public Overrides Sub VerifyRenderingInServerForm(ByVal control As System.Web.UI.Control)
            ' Verifies that the control is rendered 
            ' No code required here. 
        End Sub
    This does fire when it hits the RenderControl, and still generates the same error. So it was not a fix for me. Note, but adding the Try ... Catch, it avoids crashing and seems to generate something close to what it is suppose to.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width