Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 264
  • Last Modified:

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

0
Tagom
Asked:
Tagom
  • 6
  • 6
  • 5
  • +1
3 Solutions
 
Easwaran ParamasivamCommented:
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

0
 
CodeCruiserCommented:
Do you mean you dont want to show the grid unless the button is clicked?
0
 
TagomAuthor Commented:
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.
0
What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

 
Easwaran ParamasivamCommented:
Your page_load is in your Default.aspx.cs . I hope your grid will be also there. I just want to create a simple empty aspx page and launch the page on download button click event and write the code (to perform download operation) in the newly created page.

I hope you got my point.
0
 
CodeCruiserCommented:
>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

0
 
CodeCruiserCommented:
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

0
 
TagomAuthor Commented:
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!

0
 
yogsoftCommented:
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.
0
 
CodeCruiserCommented:
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.
0
 
TagomAuthor Commented:
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.
0
 
TagomAuthor Commented:
@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"
0
 
yogsoftCommented:
Please check my solution it is tested properly.
0
 
Easwaran ParamasivamCommented:
The below line

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

should be written as

  strbldr.Append(cell.Text).Append(",");
0
 
yogsoftCommented:
If you want to use the same code... use following line...

strbldr.Append(col.Text + ','); in place of strbldr.Append(cell.Text + ',');

cell is not changed col that is why its giving error...
0
 
yogsoftCommented:
Corrected line

strbldr.Append(col.ColumnName + ','); in place of strbldr.Append(cell.Text + ',');
0
 
CodeCruiserCommented:
Yes my bad. Change

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

to

strbldr.Append(col.ColumnName + ',');
0
 
TagomAuthor Commented:
@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"

0
 
CodeCruiserCommented:
So its refusing to convert int to string. Strange

Try changing

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

to

strbldr.Append(Convert.ToString(cell) + ',');
0
 
yogsoftCommented:
@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.

0
 
TagomAuthor Commented:
Thank all of you so much!
0

Featured Post

[Webinar On Demand] Database Backup and Recovery

Does your company store data on premises, off site, in the cloud, or a combination of these? If you answered “yes”, you need a data backup recovery plan that fits each and every platform. Watch now as as Percona teaches us how to build agile data backup recovery plan.

  • 6
  • 6
  • 5
  • +1
Tackle projects and never again get stuck behind a technical roadblock.
Join Now