views:

620

answers:

1

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?

A: 

I've found a lot of people with problems like this one, but very few answers that could help me.

Until this one: http://forums.asp.net/p/1229438/2216336.aspx#2216336

This can really solve my problem. I've done some testing and it works. He managed to save the Template fields in cache and restore them on Page_Load. Clever.

If someone finds a better solution, please post it here. It can be very useful for other fellow developers that are banging their heads on the wall.

Nelson Reis
You should create your template fields on Init (override or event). The Request is available at that point and all controls will have their state preserved. No need to cache anything.
Ruslan