Wrox Programmer Forums
Go Back   Wrox Programmer Forums > ASP.NET and ASP > ASP.NET 2.0 > ASP.NET 2.0 Basics
|
ASP.NET 2.0 Basics If you are new to ASP or ASP.NET programming with version 2.0, this is the forum to begin asking questions. Please also see the Visual Web Developer 2005 forum.
Welcome to the p2p.wrox.com Forums.

You are currently viewing the ASP.NET 2.0 Basics section of the Wrox Programmer to Programmer discussions. This is a community of software programmers and website developers including Wrox book authors and readers. New member registration was closed in 2019. New posts were shut off and the site was archived into this static format as of October 1, 2020. If you require technical support for a Wrox book please contact http://hub.wiley.com
 
Old November 24th, 2007, 07:10 AM
Authorized User
 
Join Date: May 2005
Posts: 28
Thanks: 0
Thanked 0 Times in 0 Posts
Send a message via MSN to shaileshk Send a message via Yahoo to shaileshk
Default

Hi,
I try below code for expert to excel data from the gride view and it's working find without any error. let me know in case any error on that .

I hope this will help to you.

Code:
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 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.Text;

using 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);

 

          // 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();

}


 

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

            }

        }

    }

}

shailesh kavathiya
 
Old December 4th, 2008, 07:31 AM
Registered User
 
Join Date: Dec 2008
Posts: 1
Thanks: 0
Thanked 0 Times in 0 Posts
Default

I get the below error when data around 20k with the sample from shaileshk. Please kindly advice, thanks a lot.

I only have 1 form tag in the aspx file.
From the export code:
HtmlForm frm = new HtmlForm();

Will this form been counted as 1?


Server Error in '/MyWeb' Application.
--------------------------------------------------------------------------------

A page can have only one server-side Form tag.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.Web.HttpException: A page can have only one server-side Form tag.

Source Error:

An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.

Stack Trace:


[HttpException (0x80004005): A page can have only one server-side Form tag.]
   System.Web.UI.Page.OnFormRender() +2074393
   System.Web.UI.HtmlControls.HtmlForm.RenderChildren (HtmlTextWriter writer) +28
   System.Web.UI.HtmlControls.HtmlForm.Render(HtmlTex tWriter output) +68
   System.Web.UI.Control.RenderControlInternal(HtmlTe xtWriter writer, ControlAdapter adapter) +25
   System.Web.UI.Control.RenderControl(HtmlTextWriter writer, ControlAdapter adapter) +121
   System.Web.UI.HtmlControls.HtmlForm.RenderControl( HtmlTextWriter writer) +37
   System.Web.UI.Control.RenderChildrenInternal(HtmlT extWriter writer, ICollection children) +199
   System.Web.UI.Control.RenderChildren(HtmlTextWrite r writer) +20
   System.Web.UI.Page.Render(HtmlTextWriter writer) +26
   System.Web.UI.Control.RenderControlInternal(HtmlTe xtWriter writer, ControlAdapter adapter) +25
   System.Web.UI.Control.RenderControl(HtmlTextWriter writer, ControlAdapter adapter) +121
   System.Web.UI.Control.RenderControl(HtmlTextWriter writer) +22
   System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +2558




--------------------------------------------------------------------------------
Version Information: Microsoft .NET Framework Version:2.0.50727.1434; ASP.NET Version:2.0.50727.1434

 
Old July 15th, 2009, 04:57 PM
Authorized User
 
Join Date: Jun 2009
Posts: 66
Thanks: 22
Thanked 0 Times in 0 Posts
Default Export to excel HELP!

how to show export to excel link if the row number is more than 200 in ASP.NET without showing the table(with more than 200 rows) to the user?

if I put false in resultsDatagrid.Visible then the export to excel doesn't work!!!

if (count > 0 && count <= 200)
{
DataView view = ds.Tables[0].DefaultView;
resultsDatagrid.DataSource = view;
resultsDatagrid.DataBind();
resultsDatagrid.Visible = true;
resultsLabel.Text = count.ToString() + " results found.";
resultsLabel.Visible = true;
exportLinkbutton.Visible = true;
}
else if (count> 200)
{
DataView view = ds.Tables[0].DefaultView;
resultsDatagrid.DataSource = view;
resultsDatagrid.DataBind();
resultsDatagrid.Visible = true;[If I make it false then the export to excel link doesn't work........]
resultsLabel.Text = "More than 200 results found. Please Click the Export To Excel Link to Download the Results.";
resultsLabel.Visible = true;
exportLinkbutton.Visible = true;
}
else
{
resultsLabel.Text = "No results found.";
resultsLabel.Visible = true;
exportLinkbutton.Visible = false;
resultsDatagrid.Visible = false;
}


and then in the exportLinkbutton_Click method:

private void exportLinkbutton_Click(object sender, System.EventArgs e)
{
DataGridItem tblGrid=resultsDatagrid.Items[0];
ArrayList alLinks= new ArrayList();
TableCell TC;
LinkButton LB;

for(int i=0; i<tblGrid.Cells.Count - 1; i++)
{
TC=tblGrid.Cells[i];
if(TC.Controls.Count> 0)
{
LB=(LinkButton)TC.Controls[0];
resultsDatagrid.Items[0].Cells[i].Controls.Clear();
resultsDatagrid.Items[0].Cells[i].Text=LB.Text;
}
else
LB=new LinkButton();

alLinks.Add(LB);
}

Response.ContentType = "application/vnd.ms-excel";
Response.Charset = "";
resultsDatagrid.EnableViewState = false;

System.IO.StringWriter tw = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(tw);
resultsDatagrid.RenderControl(hw);
//TextWriter TW= File.CreateText(Server.MapPath("ExportToExcel.xls" ));

Response.Write(tw.ToString());
Response.End();

for(int i=0; i<tblGrid.Cells.Count - 1; i++)
{
LB = (LinkButton)alLinks[i];
//TC=tblGrid.Rows[0].Cells[i];
resultsDatagrid.Items[0].Cells[i].Controls.Add(LB);
}
}





Similar Threads
Thread Thread Starter Forum Replies Last Post
Problem in exporting data into pdf santhoshsanjeevi J2EE 0 April 3rd, 2008 06:15 AM
Problem in exporting data from datagrid to Excel deb_kareng ASP.NET 2.0 Professional 4 August 4th, 2007 09:21 AM
Problem Exporting Data... mat41 SQL Server 2000 1 September 29th, 2005 08:35 PM
Exporting data to excel from datagrid, Problem. swadhinm ASP.NET 1.x and 2.0 Application Design 0 May 31st, 2005 01:44 AM
Problem in exporting data to PDF vasansrini Crystal Reports 1 December 10th, 2004 11:48 AM





Powered by vBulletin®
Copyright ©2000 - 2020, Jelsoft Enterprises Ltd.
Copyright (c) 2020 John Wiley & Sons, Inc.