当用GridView导出Execl的时候,会发生只能在执行 Render() 的过程中调用 RegisterForEventValidation的错误提示。
有两种方法可以解决以上问题:
1.修改web.config(不推荐)<pages enableEventValidation ="false" ></pages>
2.直接在导出Execl的页面修改

<%@ Page Language="C#" EnableEventValidation = "false" AutoEventWireup="true"

 CodeFile="ExportGridView.aspx.cs" Inherits="ExportGridView" %>

附:Gridview导出Execl可分页全部导出代码(C#)

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
using System.IO;

public partial class EXportTest : System.Web.UI.Page
{
    
protected void Page_Load(object sender, EventArgs e)
    
{
        
if (!Page.IsPostBack)
        
{
            BindData(); 
        }


    }

    
    
private string ConnectionString
    
{

        
get return @"Server=localhost;Database=Northwind;
        Trusted_Connection=true
"; }


    }


    

    
private void BindData()
    
{
        
// make the query 
        string query = "SELECT * FROM Categories";
        SqlConnection myConnection 
= new SqlConnection(ConnectionString);
        SqlDataAdapter ad 
= new SqlDataAdapter(query, myConnection);
        DataSet ds 
= new DataSet();
        ad.Fill(ds, 
"Categories");
        GridView1.DataSource 
= ds;
        GridView1.DataBind(); 

        
/* It's a good idea if you can Cache the DataSet */

    }


    
public override void VerifyRenderingInServerForm(Control control)
    
{

        
// Confirms that an HtmlForm control is rendered for
        the specified ASP.NET server control at run time.

    }


    
protected void Button1_Click(object sender, EventArgs e)
    
{
        Response.Clear();

        Response.AddHeader(
"content-disposition",
        
"attachment;filename=FileName.xls");

        Response.Charset 
= "";

        
// If you want the option to open the Excel file without saving than

        
// comment out the line below

        
// Response.Cache.SetCacheability(HttpCacheability.NoCache);

        Response.ContentType 
= "application/vnd.xls";

        System.IO.StringWriter stringWrite 
= new System.IO.StringWriter();

        System.Web.UI.HtmlTextWriter htmlWrite 
=
        
new HtmlTextWriter(stringWrite);

        
// turn off paging 
        GridView1.AllowPaging = false;
        BindData(); 
        

        GridView1.RenderControl(htmlWrite);

        Response.Write(stringWrite.ToString());

        Response.End();

        
// turn the paging on again 
        GridView1.AllowPaging = true;
        BindData();
        
    }

   
    
protected void GridView1_PageIndexChanging(object sender,
    GridViewPageEventArgs e)
    
{
        GridView1.PageIndex 
= e.NewPageIndex;
        BindData(); 
    }

}
VB.net:(GridView直接帮定DataSource控件)
Imports Microsoft.VisualBasic
Imports System
Imports System.IO


Partial 
Class ManageContents
    
Inherits System.Web.UI.Page

    
Protected Sub Page_Load(ByVal sender As ObjectByVal e As System.EventArgs) Handles Me.Load
        
'If Not Me.IsPostBack Then
        '    If Request.QueryString("username") <> "xucanzhao" Then
        '        Response.Redirect("default.aspx?returnUrl=nousername")
        '    End If
        'End If
        ' ClientScript.RegisterStartupScript(Me.GetType(), "haha", "<script>alert('haha');</script>")
    End Sub


    
Protected Sub btnExportExcel_Click(ByVal sender As ObjectByVal e As System.EventArgs) Handles btnExportExcel.Click
        Response.Clear()
        Response.Buffer 
= True

        Response.Charset 
= "utf-8"

        Response.AddHeader(
"Content-Disposition""attachment;filename=FileFlow.xls")
        Response.ContentType 
= "application/ms-excel"
        
Dim strWriter As New StringWriter()
        
Dim htw As New HtmlTextWriter(strWriter)
        GridView1.AllowPaging 
= False
        GridView1.DataBind()
        GridView1.RenderControl(htw)
        Response.Write(strWriter.ToString)
        Response.End()
        GridView1.AllowPaging 
= True
        GridView1.DataBind()
    
End Sub

    
Public Overrides Sub verifyRenderingInServerForm(ByVal control As Control)

    
End Sub

End Class


For more information:visti http://geekswithblogs.net
posted on 2006-04-29 13:22 徐灿钊Asp.net专栏 阅读(6365) 评论(13)  编辑 收藏 所属分类: .net2.0

  回复  引用  查看    
2007-04-18 17:34 | 无锋不起浪      

  回复  引用    
2007-05-08 11:56 | 何海堂 [未注册用户]
谢谢,我正好遇到这个问题
  回复  引用    
2007-05-15 09:44 | 得到 [未注册用户]
这样的话其他注册控件无法识别!!
  回复  引用    
2007-07-16 10:58 | xiaojing [未注册用户]
thank you very much!
  回复  引用    
2007-08-06 17:14 | .net [未注册用户]
嗨,哥们,帮我我的大忙啊。多谢了。
  回复  引用    
2007-09-07 14:51 | ty [未注册用户]
谢谢!
  回复  引用    
2007-10-10 23:19 | Hugo [未注册用户]
im having this problem. "RegisterForEventValidation can only be called during Render();"

my code is.

protected void Button1_Click(object sender, EventArgs e)
{

//Export the GridView to Excel

PrepareGridViewForExport(GridView1);

ExportGridView();
}
private void ExportGridView()
{
string attachment = "attachment; filename=Contacts.xls";
Response.ClearContent();
Response.AddHeader("content-disposition", attachment);
Response.ContentType = "application/ms-excel";
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
GridView1.RenderControl(htw);
Response.Write(sw.ToString());
Response.End();
}
public override void VerifyRenderingInServerForm(Control control)
{

}



private void PrepareGridViewForExport(Control gv)
{

LinkButton lb = new LinkButton();

Literal l = new Literal();

string name = String.Empty;

for (int i = 0; i < gv.Controls.Count; i++)
{

if (gv.Controls[i].GetType() == typeof(LinkButton))
{

l.Text = (gv.Controls[i] as LinkButton).Text;

gv.Controls.Remove(gv.Controls[i]);

gv.Controls.AddAt(i, l);

}

else if (gv.Controls[i].GetType() == typeof(DropDownList))
{

l.Text = (gv.Controls[i] as DropDownList).SelectedItem.Text;

gv.Controls.Remove(gv.Controls[i]);

gv.Controls.AddAt(i, l);

}

else if (gv.Controls[i].GetType() == typeof(CheckBox))
{

l.Text = (gv.Controls[i] as CheckBox).Checked ? "True" : "False";

gv.Controls.Remove(gv.Controls[i]);

gv.Controls.AddAt(i, l);

}

if (gv.Controls[i].HasControls())
{

PrepareGridViewForExport(gv.Controls[i]);

}

}

}
  回复  引用    
2007-11-15 10:48 | mu mu [未注册用户]
在Excel里没有分页? ......................
  回复  引用  查看    
2008-01-30 15:32 | mingal      
谢谢!
  回复  引用    
2008-02-01 13:53 | huhuhuhuh [未注册用户]
怎么导入到Excel里的只有GridView里面的第一页数据,后面的数据没有导入啊
  回复  引用    
2008-04-19 22:14 | sd [未注册用户]
[code]protected void Button1_Click(object sender, EventArgs e)
{
Response.Clear();
Response.Buffer = true;
Response.Charset = "GB2312";
Response.AppendHeader("Content-Disposition", "attachment;filename=FileName.xls");
// 如果设置为 GetEncoding("GB2312");导出的文件将会出现乱码!!!
Response.ContentEncoding = System.Text.Encoding.UTF7;
Response.ContentType = "application/ms-excel";//设置输出文件类型为excel文件。
System.IO.StringWriter oStringWriter = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter oHtmlTextWriter = new System.Web.UI.HtmlTextWriter(oStringWriter);
this.GridView1.RenderControl(oHtmlTextWriter);
Response.Output.Write(oStringWriter.ToString());
Response.Flush();
Response.End();

}
public override void VerifyRenderingInServerForm(Control control)
{ }
[/code]
  回复  引用    
2008-05-19 09:58 | 121 [未注册用户]
--引用--------------------------------------------------
huhuhuhuh: 怎么导入到Excel里的只有GridView里面的第一页数据,后面的数据没有导入啊
--------------------------------------------------------

  回复  引用  查看    
2008-06-22 22:31 | wuliangbo      
顶 谢谢楼主

标题  
姓名  
主页
Email (只有博主才能看到) 
验证码 *  看不清,换一张 [登录][注册]
内容(请不要发表任何与政治相关的内容)  
  登录  使用高级评论  新用户注册  返回页首  恢复上次提交      
该文被作者在 2006-04-29 13:25 编辑过