Avatar of Tagom
Tagom

asked on 

gridview file printed to webpage too large

Originally I tried to write this page to load to wepage and give option to save as csv.
The amount of data in the table it quite large and slows down response time.
I would like to only give the option to download the file via the button - I have tried to comment out the table code in the front end but then I get an error.
suggestions?
front code: aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!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></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:Button ID="cmdSend" runat="server" Text="Download File" 
            onclick="cmdSend_Click" /></br>
        </br>
        <asp:GridView ID="GridView1" AutoGenerateColumns="True" runat="server" />
    </div>
    </form>
</body>
</html>

Open in new window

aspx.cs backend
using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.IO;
using System.Data;
using System.Data.OleDb;
using System.Text;


public partial class _Default : System.Web.UI.Page
{
    private const string MDBFILE = "~/hgdeposition/App_Data/hgweb.mdb";



    private string GetConnectionString()
        {
            return "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + Server.MapPath(MDBFILE) + ";";
        }

      
    protected void Page_Load(object sender, EventArgs e)
    {
        string SQL = "SELECT * FROM RainEvents";
         if(!Page.IsPostBack){ 
        // Create Connection object
        OleDbConnection dbConn = new OleDbConnection(GetConnectionString());

        // Create Command Object
        OleDbCommand dbComm = new OleDbCommand(SQL, dbConn);

        // Open Connection
        dbConn.Open();

        // Execute command and receive DataReader
        OleDbDataReader dbRead = dbComm.ExecuteReader();

        GridView1.DataSource = dbRead;
        GridView1.DataBind();

        dbConn.Close();
        
         }
    }
    
    public override void VerifyRenderingInServerForm(Control control)
    {
        /* Verifies that the control is rendered */
    }
    /// <summary>
    /// This event is used to export gridview data to CSV document
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    
    protected void cmdSend_Click(object sender, EventArgs e)
    {
        Response.ClearContent();
        Response.AddHeader("content-disposition", string.Format("attachment; filename={0}", "File.csv"));
        Response.ContentType = "application/text";
        GridView1.AllowPaging = false;

        StringBuilder strbldr = new StringBuilder();
        foreach (TableCell cell in GridView1.HeaderRow.Cells)
        {
            //separting header columns text with comma operator
            strbldr.Append(cell.Text + ',');
        }
        //appending new line for gridview header row
        strbldr.Append("\n");
        foreach (GridViewRow gvr in GridView1.Rows)
        {
            foreach (TableCell cell in gvr.Cells)
            {
                //separating gridview columns with comma
                strbldr.Append(cell.Text + ',');
            }

            //appending new line for gridview rows
            strbldr.Append("\n");
        }
        Response.Write(strbldr.ToString());
        Response.End();
    }
}

Open in new window

ASP.NETProgramming Languages-OtherVisual Basic.NET

Avatar of undefined
Last Comment
Tagom
Avatar of Easwaran Paramasivam
Easwaran Paramasivam
Flag of India image

What you have written in the cmdSend_Click should go to be in seperate page. So that the page life cycle of your page wont be affected.


 Please do refer below sample code.
protected void cmdSend_Click(object sender, EventArgs e)
    {
        GridView1.AllowPaging = false;

        StringBuilder strbldr = new StringBuilder();
        foreach (TableCell cell in GridView1.HeaderRow.Cells)
        {
            //separting header columns text with comma operator
            strbldr.Append(cell.Text + ',');
        }
        //appending new line for gridview header row
        strbldr.Append("\n");
        foreach (GridViewRow gvr in GridView1.Rows)
        {
            foreach (TableCell cell in gvr.Cells)
            {
                //separating gridview columns with comma
                strbldr.Append(cell.Text + ',');
            }

            //appending new line for gridview rows
            strbldr.Append("\n");
        }
       //Keep the value in Session
      Session.Add("cvscontent",strbldr.ToString());

      //Redirect to new page
     Response.Redirect("YourAnotherPage.aspx",false);

  }


In your YourAnotherPage.aspx.cs file's Page_Load() method write below code:

Response.ClearContent();
        Response.AddHeader("content-disposition", string.Format("attachment; filename={0}", "File.csv"));
        Response.ContentType = "application/text";
         Response.Write(Session["cvscontent"].ToString());
        Response.End();

Open in new window

Avatar of Nasir Razzaq
Nasir Razzaq
Flag of United Kingdom of Great Britain and Northern Ireland image

Do you mean you dont want to show the grid unless the button is clicked?
Avatar of Tagom
Tagom

ASKER

EaswaranP: are you saying that I should have 3 files?
My page_load is in my Default.aspx.cs page
You can not inherit more than one page so how would I split it into three. I am lost.

CodeCruiser: Actually I would like the grid to not load at all, I just want to be able to download the csv file.
SOLUTION
Avatar of Easwaran Paramasivam
Easwaran Paramasivam
Flag of India image

Blurred text
THIS SOLUTION IS ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
Avatar of Nasir Razzaq
Nasir Razzaq
Flag of United Kingdom of Great Britain and Northern Ireland image

>Actually I would like the grid to not load at all, I just want to be able to download the csv file.

Try following code. Note that there is no grid


 
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!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></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:Button ID="cmdSend" runat="server" Text="Download File" 
            onclick="cmdSend_Click" /></br>
        </br>
        <asp:GridView ID="GridView1" AutoGenerateColumns="True" runat="server" />
    </div>
    </form>
</body>
</html>

Open in new window





 
using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.IO;
using System.Data;
using System.Data.OleDb;
using System.Text;


public partial class _Default : System.Web.UI.Page
{
    private const string MDBFILE = "~/hgdeposition/App_Data/hgweb.mdb";



    private string GetConnectionString()
        {
            return "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + Server.MapPath(MDBFILE) + ";";
        }

      
    protected void Page_Load(object sender, EventArgs e)
    {
    }
    
    /// <summary>
    /// This event is used to export datatable to CSV document
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    
    protected void cmdSend_Click(object sender, EventArgs e)
    {
        string SQL = "SELECT * FROM RainEvents";
        DataTable dTable = new DataTable();
        OleDbDataAdapter dbadp = new OleDbDataAdapter(SQL, GetConnectionString());
        dbadp.Fill(dTable);
        dbadp.Dispose();

        Response.ClearContent();
        Response.AddHeader("content-disposition", string.Format("attachment; filename={0}", "File.csv"));
        Response.ContentType = "application/text";

        StringBuilder strbldr = new StringBuilder();
        foreach (DataColumn col in dTable.Columns)
        {
            //separting header columns text with comma operator
            strbldr.Append(cell.Text + ',');
        }
        //appending new line for gridview header row
        strbldr.Append("\n");
        foreach (DataRow row in dTable.Rows)
        {
            foreach (Object cell in row.ItemArray)
            {
                //separating gridview columns with comma
                strbldr.Append((string)cell + ',');
            }

            //appending new line for gridview rows
            strbldr.Append("\n");
        }
        Response.Write(strbldr.ToString());
        Response.End();
    }
}

Open in new window

Avatar of Nasir Razzaq
Nasir Razzaq
Flag of United Kingdom of Great Britain and Northern Ireland image

Oops. Your aspx needs to be changed for me to be able to say "there is no grid"



<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!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></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:Button ID="cmdSend" runat="server" Text="Download File" 
            onclick="cmdSend_Click" /></br>
        </br>
    </div>
    </form>
</body>
</html>

Open in new window

Avatar of Tagom
Tagom

ASKER

I understand the concept, not sure how to implement.
Forgive me for being dense. I do not usually work in asp
Her is my current Default.aspx.cs page
using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.IO;
using System.Data;
using System.Data.OleDb;
using System.Text;


public partial class _Default : System.Web.UI.Page
{
    private const string MDBFILE = "~/hgdeposition/App_Data/hgweb.mdb";



    private string GetConnectionString()
        {
            return "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + Server.MapPath(MDBFILE) + ";";
        }

      
    protected void Page_Load(object sender, EventArgs e)
    {
        string SQL = "SELECT * FROM RainEvents";
         if(!Page.IsPostBack){ 
        // Create Connection object
        OleDbConnection dbConn = new OleDbConnection(GetConnectionString());

        // Create Command Object
        OleDbCommand dbComm = new OleDbCommand(SQL, dbConn);

        // Open Connection
        dbConn.Open();

        // Execute command and receive DataReader
        OleDbDataReader dbRead = dbComm.ExecuteReader();

        GridView1.DataSource = dbRead;
        GridView1.DataBind();

        dbConn.Close();
        
         }
    }
    
    public override void VerifyRenderingInServerForm(Control control)
    {
        /* Verifies that the control is rendered */
    }
    /// <summary>
    /// This event is used to export gridview data to CSV document
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    
    protected void cmdSend_Click(object sender, EventArgs e)
    {
        Response.ClearContent();
        Response.AddHeader("content-disposition", string.Format("attachment; filename={0}", "File.csv"));
        Response.ContentType = "application/text";
        GridView1.AllowPaging = false;

        StringBuilder strbldr = new StringBuilder();
        foreach (TableCell cell in GridView1.HeaderRow.Cells)
        {
            //separting header columns text with comma operator
            strbldr.Append(cell.Text + ',');
        }
        //appending new line for gridview header row
        strbldr.Append("\n");
        foreach (GridViewRow gvr in GridView1.Rows)
        {
            foreach (TableCell cell in gvr.Cells)
            {
                //separating gridview columns with comma
                strbldr.Append(cell.Text.Replace("&nbsp;", String.Empty) + ',');
            }

            //appending new line for gridview rows
            strbldr.Append("\n");
        }
        Response.Write(strbldr.ToString());
        Response.End();
    }
}

Open in new window

your are saying that I should remove my protected void cmdSend_Click portion of code?
move the below code to the page_load to

Response.ClearContent();
        Response.AddHeader("content-disposition", string.Format("attachment; filename={0}", "File.csv"));
        Response.ContentType = "application/text";
         Response.Write(Session["cvscontent"].ToString());
        Response.End();
and have my Default.aspx blank?
What page would I put the cmdSend code in AND how would I call it from the blank page....
Again sorry for the denseness!

Avatar of yogsoft
yogsoft
Flag of India image

1. Removed GridView control from aspx page.
2. Clean your Page_Load method.

3. Replace following code in cmdSend_Click method

 
Response.ClearContent();
            Response.AddHeader("content-disposition", string.Format("attachment; filename={0}", "File.csv"));
            Response.ContentType = "application/text";
           
            string SQL = "SELECT * FROM FSUdata ";

            // Create Connection object
            OleDbConnection dbConn = new OleDbConnection(GetConnectionString());

            // Create Command Object
            OleDbCommand dbComm = new OleDbCommand(SQL, dbConn);

            // Open Connection
            dbConn.Open();

            StringBuilder strbldr = new StringBuilder(); 
            // Execute command and receive DataReader
            using (OleDbDataReader dbRead = dbComm.ExecuteReader())
            {

                for (int i=0; i< dbRead.FieldCount;i++)
                {
                    //separting header columns text with comma operator
                    strbldr.Append(dbRead.GetName(i) + ',');
                }

                //appending new line for gridview header row
                strbldr.Append("\n");

                while (dbRead.Read())
                {
                    for (int i=0; i< dbRead.FieldCount;i++)
                    {
                        //separating gridview columns with comma
                        strbldr.Append(Convert.ToString(dbRead[i]) + ',');
                    }

                    //appending new line for gridview rows
                    strbldr.Append("\n");
                }
            }
            Response.Write(strbldr.ToString());
            Response.End();

Open in new window



This will work as what you wanted, let me know in case of any issue.
Note: DataReader are faster than DataTable.
Avatar of Nasir Razzaq
Nasir Razzaq
Flag of United Kingdom of Great Britain and Northern Ireland image

I gave you the actual code. Removed gridview, nothing in page load, and in btnSend, I am loading a DataTable and then looping through it to generate the CSV file.
Avatar of Tagom
Tagom

ASKER

I am at work right now and can not get to putting this in the files. I will as this afternoon! Thank all of you so much.
Avatar of Tagom
Tagom

ASKER

@codeCrusier - I get the following error with the code you posted:
Compiler Error Message: CS0103: The name 'cell' does not exist in the current context

Source Error:

Line 49:         {
Line 50:             //separting header columns text with comma operator
Line 51:             strbldr.Append(cell.Text + ',');
Line 52:         }

how do i declare "cell"
Avatar of yogsoft
yogsoft
Flag of India image

Please check my solution it is tested properly.
The below line

 strbldr.Append(cell.Text + ',');

should be written as

  strbldr.Append(cell.Text).Append(",");
SOLUTION
Avatar of yogsoft
yogsoft
Flag of India image

Blurred text
THIS SOLUTION IS ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
Avatar of yogsoft
yogsoft
Flag of India image

Corrected line

strbldr.Append(col.ColumnName + ','); in place of strbldr.Append(cell.Text + ',');
ASKER CERTIFIED SOLUTION
Avatar of Nasir Razzaq
Nasir Razzaq
Flag of United Kingdom of Great Britain and Northern Ireland image

Blurred text
THIS SOLUTION IS ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
Avatar of Tagom
Tagom

ASKER

@yogsoft and @codeCruiser
Replaced the line of code and this is the error I recieved when the download button is clicked:
Exception Details: System.InvalidCastException: Unable to cast object of type 'System.Int32' to type 'System.String'.

Source Error:

Line 58:             {
Line 59:                 //separating gridview columns with comma
Line 60:                 strbldr.Append((string)cell + ',');
Line 61:             }
Line 62:
 @EaswaranP: this change did not compile

@yogsoft - I will have to go back to the original code to see if I can figure out how to alter what I did have. Was a little confused on "what to clean out of page_load"

Avatar of Nasir Razzaq
Nasir Razzaq
Flag of United Kingdom of Great Britain and Northern Ireland image

So its refusing to convert int to string. Strange

Try changing

strbldr.Append((string)cell + ',');

to

strbldr.Append(Convert.ToString(cell) + ',');
Avatar of yogsoft
yogsoft
Flag of India image

@Tagom: Refer to my solution with code above (my first comment).

In your code-behind class there is method called Page_Load. Just remove all statements in that method. This method should look like as below.

 
protected void Page_Load(object sender, EventArgs e)
 {
 }

Open in new window


Replace code in cmdSend_Click method with the code I provided in my first comment.

Avatar of Tagom
Tagom

ASKER

Thank all of you so much!
ASP.NET
ASP.NET

The successor to Active Server Pages, ASP.NET websites utilize the .NET framework to produce dynamic, data and content-driven web applications and services. ASP.NET code can be written using any .NET supported language. As of 2009, ASP.NET can also apply the Model-View-Controller (MVC) pattern to web applications

128K
Questions
--
Followers
--
Top Experts
Get a personalized solution from industry experts
Ask the experts
Read over 600 more reviews

TRUSTED BY

IBM logoIntel logoMicrosoft logoUbisoft logoSAP logo
Qualcomm logoCitrix Systems logoWorkday logoErnst & Young logo
High performer badgeUsers love us badge
LinkedIn logoFacebook logoX logoInstagram logoTikTok logoYouTube logo