GridView使用RenderControl取得HTML出現的問題

相信不少人會用下列程式碼輸出 GridView 到 EXCEL 中
protected void btnExportToExcel_Click(object sender, EventArgs e)
{
System.IO.StringWriter tw = new System.IO.StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(tw);
string excelFileName = "MyExcel.xls";
Context.Response.ContentType = "application/x-excel";
Context.Response.AddHeader("content-disposition", "attachment;filename=" + Server.UrlEncode(excelFileName));
GridView1.RenderControl(hw);
Context.Response.Write(tw.ToString());
Context.Response.End();
}

public override void VerifyRenderingInServerForm(System.Web.UI.Control control)
{
}

但是當你遇到 GridView 有分頁的時候,就會產生下列錯誤
RegisterForEventValidation 只能在 Render(); 期間呼叫

解決的方法是在<%@ Page %>中加入兩個屬性
EnableEventValidation = "false" AutoEventWireup="true"

http://www.dotblogs.com.tw/topcat/archive/2008/03/14/1336.aspx

留言

熱門文章