c# - 当 AllowSorting 设置为 true 时,将 GridView 导出到 Excel 不起作用

标签 c# asp.net gridview

我在 GridView 中通过 ObjectDataSource 显示来自 Sql 数据库的一些数据。我还允许用户使用以下代码将数据导出到 excel:

  public override void VerifyRenderingInServerForm(Control control)
{

}



private void ExportGridToExcel()
{
    Response.Clear();
    Response.Buffer = true;
    Response.ClearContent();
    Response.ClearHeaders();
    Response.Charset = "";
    string FileName = "Results" + DateTime.Now + ".xls";
    StringWriter strwritter = new StringWriter();
    HtmlTextWriter htmltextwrtter = new HtmlTextWriter(strwritter);
    Response.Cache.SetCacheability(HttpCacheability.NoCache);
    Response.ContentType = "application/vnd.ms-excel";
    Response.AddHeader("Content-Disposition", "attachment;filename=" + FileName);
    GridView1.GridLines = GridLines.Both;
    GridView1.HeaderStyle.Font.Bold = true;
    GridView1.RenderControl(htmltextwrtter);
    Response.Write(strwritter.ToString());
    Response.End();

}


protected void Button3_Click(object sender, EventArgs e)
{
    ExportGridToExcel();
}

一切正常。但是,当我在 GridView 中设置 AllowSorting=true 并单击导出按钮时,出现以下错误:ystem.InvalidOperationException:

RegisterForEventValidation can only be called during Render();

这不是一个大问题,因为我不一定需要允许在 GridView 中进行排序,但我很好奇问题是什么?

最佳答案

将此属性添加到@Page 声明中:

EnableEventValidation="false"

关于c# - 当 AllowSorting 设置为 true 时,将 GridView 导出到 Excel 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33738987/

相关文章:

asp.net - Sitecore 检测到项目保存在 EventDisabler() 上下文中

javascript - CSS 扩展,悬停时隐藏内容

winforms - Powershell CLI 中的 GUI 和 PSRemoting

C# 在 Windows 7 中隐藏任务栏

asp.net - OutputCache 指令在 Asp.Net 中不起作用

c# - Container.Register(Type, Assembly[]) 不注册泛型实现

c# - 如何修复 ASP.NET 网站中的 EmbeddedRessources?

C#:GridView、逐行操作

C# 程序使系统崩溃立即停止(用于系统可恢复性测试),模拟严重的硬件错误

c# - 向序列化的 XML 元素添加前缀