The new GridView control in ASP.net 2.0 is a powerful data display control that shows many of the basic usage and techniques in the previous series (see <<asp.net 2.0 for the GridView control Advanced Techniques >>, <<asp.net2.0 uses GridView to realize master-slave relationship >>). In this article, you will continue to explore the techniques involved.
One, the content in the GridView export to Excel
In daily work, it's often important to export the contents of the GridView to an Excel report, and in ASP.net 2.0, it's also easy to export the contents of the entire GridView to an Excel report, as described in the following ways:
First, create a basic page default.aspx
<form id="form1" runat="server">
<div>
<asp:GridView ID="GridView1" runat="server">
</asp:GridView>
</div>
<br/>
<asp:Button ID="BtnExport" runat="server" OnClick="BtnExport_Click"
Text="Export to Excel" />
</form>
In Default.aspx.cs, write the following code:
protected void Page_Load (object sender, EventArgs e)
{
if (! Page.IsPostBack)
{
Binddata ();
}
private void Binddata ()
{
String query = "SELECT * from Customers";
SqlConnection myconnection = new SqlConnection (ConnectionString);
SqlDataAdapter ad = new SqlDataAdapter (query, MyConnection); The
DataSet ds = new DataSet ();
AD. Fill (ds, "Customers");
Gridview1.datasource = ds;
Gridview1.databind ();
}
public override void Verifyrenderinginserverform [Control control]
{
//confirms that a HtmlForm con Trol is rendered for
}
protected void Button1_Click (object sender, EventArgs e)
{
Response.Clear ();
Response.AddHeader ("Content-disposition", "Attachment;filename=filename.xls");
Response.Charset = "gb2312";
Response.ContentType = "Application/vnd.xls";
System.IO.StringWriter stringwrite = new System.IO.StringWriter ();
System.Web.UI.HtmlTextWRiter Htmlwrite =new HtmlTextWriter (Stringwrite);
Gridview1.allowpaging = false;
Binddata ();
Gridview1.rendercontrol (Htmlwrite);
Response.Write (Stringwrite.tostring ());
Response.End ();
Gridview1.allowpaging = true;
Binddata ();
}
protected void paging (Object Sender,gridviewpageeventargs e)
{
Gridview1.pageindex = e.newpageindex;< br> Binddata ();
}
In the above code, we first bind the GridView to the specified data source, and then write the relevant code in the Button1 button (which is used to export to Excel). Here use Response.AddHeader ("Content-disposition", "Attachment;filename=exporttoexcel.xls"); The file name of the Excel that you want to export, here is Exporttoexcel.xls. Note that because the contents of the GridView may be paginated, the AllowPaging property of the GridView is set to False for each time you export Excel, and then the GridView of the current page is exported through page flow to Excel. Finally, reset its AllowPaging property. Also note that you want to write an empty Verifyrenderinginserverform method (which must be written) to make sure that the HtmlForm control is rendered for the specified ASP.net server control at run time.