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: 268
  • Last Modified:

trying to iron out the last few errors

I am working on a website that returns data to a csv file...I know that the errors are in the lack of declaration of the the variables - however not sure how to declare them.
aspx :: pretty sure there are no errors here
<%@ 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" />
        
        
    </div>
    </form>
</body>
</html>

Open in new window

aspx.cs page::this page contains the errors
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;


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

Open in new window

errors:
namespace 'StringBuilder' coun not be found
fsudata does not exist
Additionally I am not sure how to create the button to call the btnCSV_Click class
0
Tagom
Asked:
Tagom
  • 3
  • 2
1 Solution
 
Jacques Bourgeois (James Burger)PresidentCommented:
StringBuilder is in the System.Text namespace, so add a using statement on that namespace at the beginning of the file.

You are using something that looks like a DataTable or a grid called FSUdata, but the system does not find a declaration for that variable.

For the button, add a button on your page and double click on it. It will generate a new procedure linked with the click of the button. Transfer you code in that new procedure and get rid of btnCSV_Click.
0
 
TagomAuthor Commented:
I fixed most errors listed above. BTW, thanks for the button hint!
I changed the fsudata (which is actually the name of the column in the database I am reading from) to Gridview1, which is the actual grid being read into the page - it is the page_load class.
here is the new 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

aspx.cs
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

This error, I see that what is happening is I closed my dataconnection which was opened in the page_load class,
I do not know how to fix this or where to go from here.
0
 
TagomAuthor Commented:
opps here is the error
Exception Details: System.InvalidOperationException: Invalid attempt to call FieldCount when reader is closed.

Source Error:

Line 61:         Response.ContentType = "application/text";
Line 62:         GridView1.AllowPaging = false;
Line 63:         GridView1.DataBind();
Line 64:         StringBuilder strbldr = new StringBuilder();
Line 65:         for (int i = 0; i < GridView1.Columns.Count; i++)
0
 
Jacques Bourgeois (James Burger)PresidentCommented:
You are rebinding the GridView on line 63. Since it was binded with dbRead, it tries to reuse the reader, but the reader cannot work because the connection used by the reader is closed.

Anyway, even if the connection was still opened, the DataReader had done its work. A DataReader is sequential, forward only. Once the data is read, it becomes useless.

I do a lot of VB and ADO.NET, but I have done almost no ASP, so I to not always see the whole thing but...

Do you really need to Bind again?

Since it seems that the system still see you DataReader in the Click event, it also probably also sees the Connection. What if you tried the following on line 63:
dbConn.Open();
GridView1.DataBind();
dbConn.Close();

Open in new window

That would possibly reopen the Connection and reset the Reader before databinging

0
 
TagomAuthor Commented:
I got this fixed:
working code:
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 ";
         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

thank you all for helping me, i have learned a lot!
0

Featured Post

Configuration Guide and Best Practices

Read the guide to learn how to orchestrate Data ONTAP, create application-consistent backups and enable fast recovery from NetApp storage snapshots. Version 9.5 also contains performance and scalability enhancements to meet the needs of the largest enterprise environments.

  • 3
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now