?
Solved

data not being returned into the csv file

Posted on 2011-10-04
8
Medium Priority
?
338 Views
Last Modified: 2012-05-12
I have a page that
1. load data from a table into a grid
2. has a button to download the file seen in the grid
ISSUE:
The code does save a file, and the grid is displayed: however there is no data stored or transferred to the file when saved. So I have a perfect grid, a file, no data.
What did I miss, do wrong or leave out to populate the csv file. Please
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:GridView ID="GridView1" AutoGenerateColumns="true" runat="server" />
        </br>
        </br>
         <asp:Button ID="cmdSend" runat="server" Text="Download File" 
            onclick="cmdSend_Click" />
        
    </div>
    </form>
</body>
</html>

Open in new window

backend file
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 = "FileUpload2.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 FSUdata ";

        // 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;
        //GridView1.DataBind();
        StringBuilder strbldr = new StringBuilder();
        for (int i = 0; i < GridView1.Columns.Count; i++)
        {
            //separting header columns text with comma operator
            strbldr.Append(GridView1.Columns[i].HeaderText + ',');
        }
        //appending new line for gridview header row
        strbldr.Append("\n");
        for (int j = 0; j < GridView1.Rows.Count; j++)
        {
            for (int k = 0; k < GridView1.Columns.Count; k++)
            {
                //separating gridview columns with comma
                strbldr.Append(GridView1.Rows[j].Cells[k].Text + ',');
            }
            //appending new line for gridview rows
            strbldr.Append("\n");
        }
        Response.Write(strbldr.ToString());
        Response.End();
    }
}

Open in new window

0
Comment
Question by:Tagom
8 Comments
 
LVL 27

Expert Comment

by:Shaun Kline
ID: 36910421
Try enclosing your data load in the Page_Load event in an if(!Page.IsPostBack)

When a button is clicked, the post back event will cause the grid to reload (if above is not included), which will cause your grid to appear empty in your button's onclick event.
0
 

Author Comment

by:Tagom
ID: 36910503
not sure where to put the code: I tried
   if(!Page.IsPostBack){
    protected void Page_Load(object sender, EventArgs e)
    {
        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();

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

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

        dbConn.Close();


    }
    }
however that gave me an error
0
 

Author Comment

by:Tagom
ID: 36910521
Changed to this:
 protected void Page_Load(object sender, EventArgs e)
    {
        string SQL = "SELECT * FROM FSUdata ";
         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();
       
         }
    }
   
which did not give me an error but still did not put data into 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.

 
LVL 83

Expert Comment

by:CodeCruiser
ID: 36910587
You did click the Send button right?
0
 

Author Comment

by:Tagom
ID: 36910635
yes!, even tried different browser in case!
it is not transferring any data to the csv file.
link is here if you want to test...if you get a file with data that is the same as grid please let me know!
http://uwf.edu/hgdeposition/DataCollections/Default.aspx
0
 
LVL 2

Accepted Solution

by:
yogsoft earned 2000 total points
ID: 36910893
@tagom: Replace following  code in cmdSend_Click method. Auto generated columns are not accessible, hence use HeaderRow.

 
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


I'm sure this will work.
0
 
LVL 83

Expert Comment

by:CodeCruiser
ID: 36910999
See if you can use the library from here

http://www.codeproject.com/KB/office/WebExcel.aspx
0
 

Author Closing Comment

by:Tagom
ID: 36911198
Works perfectly!  thank you so much!
0

Featured Post

VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Windows Script Host (WSH) has been part of Windows since Windows NT4. Windows Script Host provides architecture for building dynamic scripts that consist of a core object model, scripting hosts, and scripting engines. The key components of Window…
Calculating holidays and working days is a function that is often needed yet it is not one found within the Framework. This article presents one approach to building a working-day calculator for use in .NET.
This tutorial explains how to use the VisualVM tool for the Java platform application. This video goes into detail on the Threads, Sampler, and Profiler tabs.
Viewers will learn how to properly install Eclipse with the necessary JDK, and will take a look at an introductory Java program. Download Eclipse installation zip file: Extract files from zip file: Download and install JDK 8: Open Eclipse and …
Suggested Courses
Course of the Month13 days, 22 hours left to enroll

809 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question