So why would you want to get rid of the html hidden viewstate field from your aspx files? My reason was that I was using the gridview control on a page and changing the response.content to excel

Response.ContentType = "application/vnd.ms-excel"

to act as quick data extract into a spreadsheet - messy but it works, at least it did in classic ASP. Moving to ASP.NET and adding a form and gridview control drops in the __VIEWSTATE form field which then ends up in the first row of the spreadsheet. Yuck - not what I wanted. A little googling later and I’d thought I’d found the answer in

EnableViewState="false"
  • but still the viewstate persists (if you excuse the pun).

More googling reveals that EnableViewState only does half the job. Specifically from Scott on Writing

“So even if you set the Pages EnableViewState to False, youll still get a __VIEWSTATE hidden form field with the Pages hash and ArrayList of controls that require postback. I still dont see why this is needed, but there is likely a good reason.”

One possible solution then would be to manipulate the HTML DOM after its been rendered to delete the offending element. As the page isn’t posting back, this can be done without repercussion. However, since I wanted to export to excel in this first place, a far more elegant solution presented itself with the HtmlTextWriter and StringWriter controls…

Private Sub ExportToExcel()

   Response.Clear()
   Response.AppendHeader("Content-Type", "application/vnd.ms-excel")
   Response.AppendHeader("Content-Disposition ", "attachment; filename=Attachment.csv")
   Response.Charset = ""
   Dim stringWrite As System.IO.StringWriter = New System.IO.StringWriter()
   Dim htmlWrite As System.Web.UI.HtmlTextWriter = New HtmlTextWriter(stringWrite)

   Dim f As New HtmlForm
   Me.Controls.Add(f)

   GridView1.AllowPaging = False
   GridView1.AllowSorting = False
   f.Controls.Add(GridView1)
   f.RenderControl(htmlWrite)
   Response.Write(stringWrite.ToString())
   Response.End()

End Sub

Motto? When creating a solution, don’t lose sight of the original problem.