We have been using this in classic ASP and I wanted to continue using it in ASP.NET. It works fine but I had to adjust the routine from what I found described at MSDN and all over the net. Here is what you find typically, for instance at MSDN:
|
' Set the content type to Excel. Response.ContentType = "application/vnd.ms-excel" ' Remove the charset from the Content-Type header. Response.Charset = "" ' Turn off the view state. Me.EnableViewState = False
Dim tw As New System.IO.StringWriter() Dim hw As New System.Web.UI.HtmlTextWriter(tw) ' Get the HTML for the control. Me.GridView1.RenderControl(hw) ' Write the HTML back to the browser. Response.Write(tw.ToString()) ' End the response. Response.End() |
I found that when I pasted all of this code into my Page_Load event, I got this error:
System.Web.HttpException: Control 'GridView1' of type 'GridView' must be placed inside a form tag with runat=server.
Here's what I can pass along based on my quick recovery: If I remove the .rendercontrol, .write and .end statements, the page works exactly as I want. The data loads into the gridview. The content is formatted as HTML table. The content is then offered up as something for Excel to handle, and the user has the option to open or save, either of which works just fine.
Here's what surprised me: The code on the internet that includes the lines I removed is always presented as code in some button's click event. I tried doing the same, assuming that the page, being in a different state by the time you can click a button, needed the other statements to convert properly. Well, that didn't work. I found, to my surprise, that I had to remove the same lines from the button click event and then the page worked just fine. Actually, I got a bonus out of the problem. By chasing this up a little, I found that I could let the page render as regular HTML first, give the user a button, and let the user "export" to Excel if desired. Pretty cool. I may go ahead and enable editing in the gridview, since it's an admin page anyway, and then I have an editing admin interface just pretty close to free.
My page is fine, but I'm curious to know why the code I found didn't work in the button click event. If remove the same statements outlined above, then the button works fine.
I'd love to know what's at work here that means I don't need the lines I'm removing.