0% found this document useful (0 votes)
170 views

–Gridview - To - Excel - Datatable - To - Excel.Aspx: When We Execute The Above Code, It Will Give The Following Error

The document discusses two methods for exporting data from a GridView or DataTable to Excel in ASP.NET: 1) Rendering the GridView control directly to the Response and setting the appropriate headers, 2) Populating the Response by looping through the rows and columns of a DataTable and writing the cell values to the Response. Both methods require setting the ContentType to a format Excel can read like "application/ms-excel".

Uploaded by

Prince Foru
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
170 views

–Gridview - To - Excel - Datatable - To - Excel.Aspx: When We Execute The Above Code, It Will Give The Following Error

The document discusses two methods for exporting data from a GridView or DataTable to Excel in ASP.NET: 1) Rendering the GridView control directly to the Response and setting the appropriate headers, 2) Populating the Response by looping through the rows and columns of a DataTable and writing the cell values to the Response. Both methods require setting the ContentType to a format Excel can read like "application/ms-excel".

Uploaded by

Prince Foru
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 11

From : -http://www.codedigest.com/Articles/ASPNET/130_Export_to_Excel_in_ASPNet_20_ %E2%80%93Gridview_to_Excel_DataTable_to_Excel.

aspx Export to Excel Rendering the Gridview Control to Excel Rendering the underlying DataTable to Excel

Rendering the Gridview Control to Excel This is one of the most commonly done approach where we set MIME type and use Gridviews RenderControl() method, similar to we do for a Datagrid control. string attachment = "attachment; filename=Employee.xls"; Response.ClearContent(); Response.AddHeader("content-disposition", attachment); Response.ContentType = "application/ms-excel"; StringWriter stw = new StringWriter(); HtmlTextWriter htextw = new HtmlTextWriter(stw); gvEmployee.RenderControl(htextw); Response.Write(stw.ToString()); Response.End();

When we execute the above code, it will give the following error.

Control 'gvEmployee' of type 'GridView' must be placed inside a form tag with runat=server

We can resolve the error by 2 ways, 1. Adding the Gridview to a HtmlForm object programmatically 2. Overriding VerifyRenderingInServerForm Event in the page.

Adding the Gridview to a HtmlForm object programmatically So, instead of rendering the gridview add the gridview to an HtmlForm object and render the form.

HtmlForm form = new HtmlForm(); string attachment = "attachment; filename=Employee.xls"; Response.ClearContent(); Response.AddHeader("content-disposition", attachment); Response.ContentType = "application/ms-excel"; StringWriter stw = new StringWriter(); HtmlTextWriter htextw = new HtmlTextWriter(stw); form.Controls.Add(gvEmployee); this.Controls.Add(form); form.RenderControl(htextw); Response.Write(stw.ToString()); Response.End();

This will solve the error.

Overriding VerifyRenderingInServerForm Event in the page

Adding this event in the codebehind 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) { string attachment = "attachment; filename=Employee.xls"; Response.ClearContent(); Response.AddHeader("content-disposition", attachment); Response.ContentType = "application/ms-excel"; StringWriter stw = new StringWriter(); HtmlTextWriter htextw = new HtmlTextWriter(stw); gvEmployee.RenderControl(htextw); Response.Write(stw.ToString()); Response.End(); }

public override void VerifyRenderingInServerForm(Control control) {

Recent Articles Creating Custom Configuration Section and Elements in ASP.Net Posted on 2/3/2011 @ 8:22 AM By Bala Murugan All About UpdatePanel in Asp.Net

Posted on 2/3/2011 @ 8:10 AM By Suresh Kumar Goudampally Using JQuery with GridView in asp.net Posted on 1/10/2011 @ 8:25 AM By Suresh Kumar Goudampally Caching in ASP.Net Applications Posted on 1/6/2011 @ 6:57 AM By Bala Murugan Reading and Writing XML files in C# and ASP.Net Posted on 12/30/2010 @ 7:32 AM By Satheesh Babu B Rendering the underlying DataTable to Excel This is one of the easiest ways of exporting the data to excel. The content of the DataTable should be written to the response by setting ContentType attribute to "application/vnd.ms-excel" and by setting its header.

protected void Button3_Click(object sender, EventArgs e) { DataTable dt = GetData(); string attachment = "attachment; filename=Employee.xls"; Response.ClearContent(); Response.AddHeader("content-disposition", attachment); Response.ContentType = "application/vnd.ms-excel"; string tab = ""; foreach (DataColumn dc in dt.Columns) { Response.Write(tab + dc.ColumnName); tab = "\t"; } Response.Write("\n");

int i; foreach (DataRow dr in dt.Rows) { tab = ""; for (i = 0; i < dt.Columns.Count; i++) { Response.Write(tab + dr[i].ToString()); tab = "\t"; } Response.Write("\n"); } Response.End(); } Execute the page and see export to excel in action.

From : - http://www.csharpcorner.com/uploadfile/dipalchoksi/exportxl_asp2_dc11032006003657am/exportxl_ asp2_dc.aspx

Step 1: Setup your web page with the Gridview In this article, we will assume you are starting with a web page which holds a GridView named GridView1. The GridView in our demo code is bound to a table named "ContactPhone" in a SQL Express database. The following code which exports the databound GridView to Excel is not dependent on the specific databindings and can be used without changes for your scenario. ContactPhone Table Structure: Column Name ContactID FName LName ContactPhone Step: The Actual Export The code to do the Excel Export is very straightforward. You can also export to different application type by changing the content-disposition and ContentType. 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(); If you run the code as above, it will result in an HttpException as follows: Control 'GridView1' of type 'GridView' must be placed inside a form tag with runat=server." To avoid this error, add the following code: public override void VerifyRenderingInServerForm(Control control) { Type Int (Identity) Varchar(50) Varchar(50) Varchar(20)

} Step : Convert the contents If the GridView contains any controls, such as Checkboxes, Dropdownlists, we need to replace the contents with their relevant values. The following recursive function uses Reflection to determine the type of control. The control is deleted in preparation for the Excel export and the relevant value of the control is added. 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]); }

Code Listing: Image: Page Design

Image : Sample in action Image: Export to Excel button is clicked Image: GridView contents exported to Excel

ExcelExport.aspx <%@ Page Language="C#" AutoEventWireup="true" CodeFile="ExportExcel.aspx.cs" Inherits="DeleteConfirm" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <head runat="server"> <title>Contacts Listing</title> </head> <body> <form id="form1" runat="server"> <div> <strong><span style="font-size: small; font-family: Arial; text-decoration: underline"> Contacts Listing <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Export To Excel" /></span></strong><br /> <br /> <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="ContactID" DataSourceID="SqlDataSource1" EmptyDataText="There are no data records to display." style="font-size: small; font-family: Arial" BackColor="White" BorderColor="#DEDFDE" BorderStyle="None" BorderWidth="1px" CellPadding="4" ForeColor="Black" GridLines="Vertical"> <Columns> <asp:BoundField DataField="ContactID" HeaderText="ContactID" ReadOnly="True" SortExpression="ContactID" Visible="False" /> <asp:BoundField DataField="FName" HeaderText="First Name" SortExpression="FName" /> <asp:BoundField DataField="LName" HeaderText="Last Name" SortExpression="LName" /> <asp:BoundField DataField="ContactPhone" HeaderText="Phone" SortExpression="ContactPhone" /> <asp:TemplateField HeaderText="Favorites"> <ItemTemplate> &nbsp; <asp:CheckBox ID="CheckBox1" runat="server" /> </ItemTemplate></asp:TemplateField> </Columns> <FooterStyle BackColor="#CCCC99" /> <RowStyle BackColor="#F7F7DE" /> <SelectedRowStyle BackColor="#CE5D5A" Font-Bold="True" ForeColor="White" /> <PagerStyle BackColor="#F7F7DE" ForeColor="Black" HorizontalAlign="Right" /> <HeaderStyle BackColor="#6B696B" Font-Bold="True" ForeColor="White" /> <AlternatingRowStyle BackColor="White" /> </asp:GridView> <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:ContactsConnectionString1 %>"

DeleteCommand="DELETE FROM [ContactPhone] WHERE [ContactID] = @ContactID" InsertCommand="INSERT INTO [ContactPhone] ([FName], [LName], [ContactPhone]) VALUES (@FName, @LName, @ContactPhone)" ProviderName="<%$ ConnectionStrings:ContactsConnectionString1.ProviderName %>" SelectCommand="SELECT [ContactID], [FName], [LName], [ContactPhone] FROM [ContactPhone]" UpdateCommand="UPDATE [ContactPhone] SET [FName] = @FName, [LName] = @LName, [ContactPhone] = @ContactPhone WHERE [ContactID] = @ContactID"> <InsertParameters> <asp:Parameter Name="FName" Type="String" /> <asp:Parameter Name="LName" Type="String" /> <asp:Parameter Name="ContactPhone" Type="String" /> </InsertParameters> <UpdateParameters> <asp:Parameter Name="FName" Type="String" /> <asp:Parameter Name="LName" Type="String" /> <asp:Parameter Name="ContactPhone" Type="String" /> <asp:Parameter Name="ContactID" Type="Int32" /> </UpdateParameters> <DeleteParameters> <asp:Parameter Name="ContactID" Type="Int32" /> </DeleteParameters> </asp:SqlDataSource> &nbsp; <br /> </div> </form> </body> </html> ExcelExport.aspx.cs using using using using using using using using using using using using System; System.Data; System.Configuration; System.Collections; System.Web; System.Web.Security; System.Web.UI; System.Web.UI.WebControls; System.Web.UI.WebControls.WebParts; System.Web.UI.HtmlControls; System.Text; System.IO;

public partial class DeleteConfirm : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { }

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]); }

} }

Implementation Options: In quite a few cases, developers face an error in the Export functionality - typically the error message is "RegisterForEventValidation can only be called during Render();". Our website readers have contributed some good suggestions in the article comments below. I would particularly like to highlight the suggestion by Marianna, who provides an alternative implementation to the VerifyRenderingInServerForm override. This approach is described below: Step 1: Implement the Export functionality as described above. Step 2: Remove the code to override the VerifyRenderingInServerForm method. Step 3: Modify the code for the ExportGridView function as below. The code highlighted in green creates and HtmlForm on the fly, before exporting the gridview, adds the gridview to this new form and renders the form (instead of rendering the gridview in our original implementation) 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); // Create a form to contain the grid HtmlForm frm = new HtmlForm(); GridView1.Parent.Controls.Add(frm); frm.Attributes["runat"] = "server"; frm.Controls.Add(GridView1); frm.RenderControl(htw); //GridView1.RenderControl(htw); Response.Write(sw.ToString()); Response.End();

You might also like