Error 1: The control "GridView1" of type "GridView" must be placed inside the form tag with Runat=server
Solution: Overload the Verifyrenderinginserverform method in a background file, such as:
public override void Verifyrenderinginserverform (Control control)
{
}
Error 2: registerForEventValidation can be called only in the execution of Render () (registerForEventValidation can only is called during render ();
Solution: In the source, add the Red Section <%@ page language= "C #" enableEventValidation = "false"codefile= "ExportGridView.aspx.cs" inherits= "Exportgridview"%>
In addition, when using the GridView Method GetData () to get the data is written as public DataSet GetData (), return a DS,
Invoke the event, instantiate a dataset, let it be equal to DS,
protected voidBtnexcel_click (Objectsender, EventArgs e) {grid. AllowPaging=false; Grid. AllowSorting=false; Grid. columns[7]. Visible =false; Gridbindall (); DateTime DT=DateTime.Now; stringstr = dt. ToString ("YYYYMMDDHHMMSS"); STR= str +". xls"; Gridviewtoexcel (Grid,"Application/ms-excel", str); Grid. AllowPaging=true; Grid. AllowSorting=true; Grid. columns[2]. Visible =true; Gridviewbind (); //Export (Gvrecord, "Application/ms-excel", str); } /// <summary> ///export grid data to Excel/// </summary> /// <param name= "Ctrl" >grid name (e.g. GridView1)</param> /// <param name= "FileType" >file types to export (Excel:application/ms-excel)</param> /// <param name= "FileName" >the file name to save</param> Public Static voidGridviewtoexcel (Control Ctrl,stringFileType,stringFileName) {HttpContext.Current.Response.Charset="GB2312"; HttpContext.Current.Response.ContentEncoding= System.Text.Encoding.UTF8;//Note CodingHttpContext.Current.Response.AppendHeader ("content-disposition", "attachment;filename="+Httputility.urlencode (FileName, System.Text.Encoding.UTF8). ToString ()); HttpContext.Current.Response.ContentType= FileType;//Image/jpeg;text/html;image/gif;vnd.ms-excel/mswordCtrl. Page.enableviewstate =false; StringWriter TW=NewStringWriter (); HtmlTextWriter HW=NewHtmlTextWriter (TW); Ctrl. RenderControl (HW); HttpContext.Current.Response.Write ("<meta http-equiv=\ "content-type\" content=\ "text/html; charset=utf-8\" />"+tw. ToString ()); HttpContext.Current.Response.End (); } Public Override voidVerifyrenderinginserverform (Control control) {//base. Verifyrenderinginserverform (control);}
Note: Only the columns in the GridView are exported, and none of the other columns in the database are exported.
C # GridView Export Excel table