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).
It worked fine, so I didn't thought anymore about the PostBack issue.
Now I'm trying to export that GridView to Excel. I'm using the following 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();
}
The problem is that all the columns are rendered to the Excel file except the Template fields, that are left blank.
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.
Can someone help me in this?