title: GridView with ITemplate fields export to Excel
body: <p>I have a GridView wich has some programmatically Template fields added to it on Page_Load and on every PostBack (because, for some reason, these fields loose their value on PostBack).</p>
  
  <p>It worked fine, so I didn't thought anymore about the PostBack issue.</p>
  
  <p>Now I'm trying to export that GridView to Excel. I'm using the following code:</p>
  
  <pre><code>protected void ExportToExcel_Click(object sender, EventArgs e)
  {
      string attachment = "attachment; filename=ExcelFile.xls";
      Response.ClearContent();
      Response.AddHeader("content-disposition", attachment);
      Response.ContentType = "application/vnd.xls";
      Response.Charset = "utf-8";
      Response.ContentEncoding = System.Text.Encoding.GetEncoding("windows-1250");
      StringWriter sw = new StringWriter();
      HtmlTextWriter htw = new HtmlTextWriter(sw);
  
      // Create a form to contain the grid
      HtmlForm frm = new HtmlForm();
      this.gridValores.Parent.Controls.Add(frm);
      frm.Attributes["runat"] = "server";
      frm.Controls.Add(this.gridView);
      frm.RenderControl(htw);
      Response.Write(sw.ToString());
      Response.End();
  }
  </code></pre>
  
  <p>The problem is that all the columns are rendered to the Excel file except the Template fields, that are left blank.</p>
  
  <p>I think that the problem is related with the fact that the Template fields loose their values on each PostBack. I've searched about it and found people saying that these dynamic fields should be added on Page_Init, not on Page_Load. I'm not sure this is true, nevertheless I need to create those fields based on information that I get through HttpRequest, that isn't there on Init, if I'm not mistaken.</p>
  
  <p>Can someone help me in this?</p>