1. Gridview1 must be placed in the form tag with runat = Server
Solution: InProgramAdd the followingCodeMediumGreenSome code.
// Button click event
Protected void button#click (Object sender, eventargs E)
{
Response. Clear ();
Downloadexcelflag = true;
Response. Buffer = true;
Response. charset = "gb2312"; // set the type to Chinese to prevent garbled characters.
Response. appendheader ("content-disposition", "attachment; filename =" + textbox1.text + ". xls"); // define the output file and file name
Response. contentencoding = system. Text. encoding. getencoding ("gb2312"); // set the output stream to simplified Chinese
Response. contenttype = "application/MS-excel"; // set the output file type to an Excel file.
This. enableviewstate = false;
System. Globalization. cultureinfo mycitrad = new system. Globalization. cultureinfo ("ZH-CN", true );
System. Io. stringwriter ostringwriter = new system. Io. stringwriter (mycitrad );
System. Web. UI. htmltextwriter ohtmltextwriter = new system. Web. UI. htmltextwriter (ostringwriter );
This. gridview1.rendercontrol (ohtmltextwriter );
Response. Write (ostringwriter. tostring ());
}
Bool downloadexcelflag = false;
Public override void rendercontrol (htmltextwriter writer)
{
If (downloadexcelflag)
This. gridview1.rendercontrol (writer); // output only gridview1
Else
Base. rendercontrol (writer );
}
Public override void verifyrenderinginserverform (Control)
{
If (! Downloadexcelflag)
Base. verifyrenderinginserverform (control );
}
2. If the above part is not running properly, the following error is prompted:
Registerforeventvalidation can be called only during render () execution.
Solution:
The enableeventvalidation attribute is. net Framework 2.0 is a new property. By default, the value of this property is true. asp. net checks the parameters in the POST method. If it is deemed invalid, an exception is thrown. The purpose of this design is to prevent malicious users from using the POST method to send malicious data, but sometimes there are similar errors.
If this function is disabled, the problem can be solved. You can solve this problem in two ways:
1. In the Web. config file: Add the following code in the <system. Web> </system. Web> tag:
<System. Web>
<Pages enableeventvalidation = "false"> </pages>
</System. Web>
2. on the specific. ASPX pageSource codeModify the Code as follows:
<% @ Page Language = "C #"Enableeventvalidation = "false"Autoeventwireup = "true" codefile = "gridview_export_excel.aspx.cs" inherits = "gridview_export_excel" %>