Solved

returning data to html page via datagrid

Posted on 2011-09-29
16
315 Views
Last Modified: 2012-08-13
I have not used asp in a long time _ when I studied it was asp.net 1.0!

I have agreed to help on a project but now nee help myself.

I need to present a table in a grid view.

I have the following so far:

asp.cs backend:
using System;
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;

namespace FileUpload
{

    public class WebForm1 : System.Web.UI.Page
    {
        private const string MDBFILE = "FileUpload2.mdb";

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


        // Read file out of the database and returns it to client
        private void ShowTheFile()
        {
            // Define SQL select statement
            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();

            // Read row
            dbRead.Read();

            // Clear Response buffer
            Response.Clear();

            // Set ContentType to the ContentType of our file
            Response.ContentType = (string)dbRead["ContentType"];

            // Write data out of database into Output Stream
            Response.OutputStream.Write(string)(dbRead)["ContentType"];

            // Close database connection
            dbConn.Close();

            // End the page
            Response.End();
        }

        // Reads the name of current web page
        private string GetMyName()
        {
            // Get the script name
            string strScript = Request.ServerVariables["SCRIPT_NAME"];

            // Get position of last slash
            int nPos = strScript.LastIndexOf("/");

            // Get everything after slash
            if (nPos > -1)
                strScript = strScript.Substring(nPos + 1);

            return strScript;
        }
    }
}

Open in new window

I think that I have left out the binding code but am not sure where to put it.

front code aspx
<%@ Page Language="c#" AutoEventWireup="false" CodeBehind="FSU.aspx.cs" Inherits="FileUpload.WebForm1"
    Src="FSU.aspx.cs" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<!-- TemplateBeginEditable name="doctitle" -->
	<title>Teen OutReach</title>
	<meta name="description" content="Designed and developed by Codify Design Studio - codifydesign.com" />
	
</head>
<body ms_positioning="GridLayout">

		<div class="contentArea">
			<div class="container"><!-- TemplateBeginEditable name="content" -->
				<div class="contentleft">
    <form id="Form1" method="post" runat="server" enctype="multipart/form-data">
      <asp:datagrid runat="server" id="ContentType" /> <p>&nbsp;</p>
      <p>&nbsp;</p>
      <p>&nbsp;</p>
    </form>

        </div>
</body>
</html>

Open in new window

I know this is not correct - can someone help with this.



0
Comment
Question by:Tagom
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 9
  • 7
16 Comments
 
LVL 6

Accepted Solution

by:
mjfagan earned 500 total points
ID: 36817898
You need to set your gridview's datasource and then bind it (in your asp.cs).

An example I have, in a VB.NET procedure (used an arraylist as my datasource):

 Public Sub LoadDataView(ByVal dg As GridView, ByRef data As ArrayList)
        dg.DataSource = data
        dg.DataBind()

    End Sub
0
 

Author Comment

by:Tagom
ID: 36818240
I have an aspx page with this code similar to yours and would like to move it to the aspx.cs page - however I get tons of erros...probably because I do not know where to place it!
 I have this code and it works: the issue is this is the front page and has the dataconnection information hardcoded.
I would like to use both the backend code and the front end code.
<%@ Import Namespace ="System.Data" %>
<%@ Import Namespace="System.Data.OleDB" %>
<script language="vb" runat ="server">
sub Page_Load()
        Dim strconnection As String = "Provider=Microsoft.Jet.OLEDB.4.0;"
        strconnection += "Data Source = \\domain\database\nameOF.mdb"
        Dim strSQL As String = "SELECT * FROM someTable"
        Dim objdataset As New DataSet
        Dim objconnection As New OleDbConnection(strconnection)
        Dim objadapter As New OleDbDataAdapter(strSQL, objconnection)
        objadapter.Fill(objdataset, "table1")
        Dim objdataview As New DataView(objdataset.Tables("table1"))
        nwdat.DataSource = objdataview
        nwdat.databind()
end sub
</script>
<html>
<body>
<h2> </h2>
<asp:datagrid id="nwdat" runat = "server"/>
<br />
</body>
</html>

Open in new window

0
 
LVL 6

Expert Comment

by:mjfagan
ID: 36818290
In your .cs code file, you should have a Page_Load--that's where the code to get and bind the data for the grid view should be.
0
Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 

Author Comment

by:Tagom
ID: 36818362
do you by chance have an example of this.
0
 
LVL 6

Expert Comment

by:mjfagan
ID: 36818400
I'm on my home computer now and don't have an example handy.  But from memory and assuming that you're using Visual Studio (and please keep in mind that I'm a VB.NET programmer:-)

You have your aspx form--double clicking on it should open the code behind (your .cs file).  You should see the Page_Load.

Now you need to use the code that you already have (pasted below):

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

            // Read row
            dbRead.Read();

********************

Set your grid view's datasource to dbRead (Note:  I haven't used readers in awhile--the code you have might only show one row--you might need to use a different object or comment out that last line of your code)

Close your connection.

0
 

Author Comment

by:Tagom
ID: 36818457
okay, this is where i am confused!
I do not see a Page_Load in my aspx.cs (named FSUreturn.aspx.cs
when I click on my fsuDataReturnT.aspx it does indeed open the aspx.cs page....I am confused with which page i should be placing the code for Page_load.
If you could ignore the above page that has both pieced of code in the same page....I might have confused what I have.
here is the FSUreturn.aspx
using System;
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;

namespace FileUpload
{

    public class WebForm1 : System.Web.UI.Page
    {
        private const string MDBFILE = "FileUpload2.mdb";

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


        // Read file out of the database and returns it to client
        private void ShowTheFile()
        {
            // Define SQL select statement
            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();

            // Read row
            dbRead.Read();

            // Clear Response buffer
            Response.Clear();

            // Set ContentType to the ContentType of our file
            Response.ContentType = (string)dbRead["ContentType"];

            // Write data out of database into Output Stream
            // Write data out of database into Output Stream
            Response.OutputStream.Write((byte[])dbRead["FileData"], 0, (int)dbRead["FileSize"]);

            // Close database connection
            dbConn.Close();

            // End the page
            Response.End();
        }

        // Reads the name of current web page
        private string GetMyName()
        {
            // Get the script name
            string strScript = Request.ServerVariables["SCRIPT_NAME"];

            // Get position of last slash
            int nPos = strScript.LastIndexOf("/");

            // Get everything after slash
            if (nPos > -1)
                strScript = strScript.Substring(nPos + 1);

            return strScript;
        }
    }
}

Open in new window

and her is the fsuDateReturnT.asp
<%@ Page Language="c#" AutoEventWireup="false" CodeBehind="FSU.aspx.cs" Inherits="FileUpload.WebForm1"
    Src="FSU.aspx.cs" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>

	<title>Teen OutReach</title>
	
	
</head>
<body ms_positioning="GridLayout">

		<div class="contentArea">
			<div class="container">
				<div class="contentleft">
    <form id="Form1" method="post" runat="server" enctype="multipart/form-data">
      <asp:datagrid runat="server" id="dbRead" /> <p>&nbsp;</p>

    </form>

        </div>
</body>
</html>

Open in new window

I am sure I am being dense...this is just so rusty for me!
0
 
LVL 6

Expert Comment

by:mjfagan
ID: 36818503
I just created a new web project in C#, double clicked on the default.aspx page and as you will see, that's where the Page_Load is (for the default.aspx page--each page has their own).  That's where you'll put the code.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace WebApplication1
{
    public partial class _Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }
    }
}

Open in new window

0
 

Author Comment

by:Tagom
ID: 36818725
I really appreciate all of your help. I am obviously not getting it.
0
 
LVL 6

Expert Comment

by:mjfagan
ID: 36822921
Have you been able to get to a point of seeing the Page_Load?  What version of Visual Studio are you using?  The example I showed you is from 2010.
0
 

Author Comment

by:Tagom
ID: 36825005
Hi...I have not given up.
Yes I have gotten to the point of seeing the Page_load...I now have 2010 connected to my server...
Was looking for some tutorials even on how to navigate using studio 2010.
I am new to it...usually use eclipse for jsp, faces and ms sql for reporting....very frustrated with this project!
Here is what I have so far:
aspx page
<%@ 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 runat="server" />
    </div>
    </form>
</body>
</html>

Open in new window

and the aspx.cs page
using System;
using System.Collections.Generic;
using System.Linq;
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();

        // Read row
        //dbRead.Read();


    }
}

Open in new window

and i think you are right that the dbRead:Read is one row at a time!

0
 
LVL 6

Expert Comment

by:mjfagan
ID: 36830431
Unless you're adding more to the aspx file, you don't need to include that at this point because it's all going to be in the code behind file (the .cs file).

Now you need to bind the data to the grid view.  Not sure what you named it but it would be:

GridView1.DataSource = dbRead
GridView1.DataBind()

dbConn.Close()

Of course this is in VB.NET.

0
 

Author Comment

by:Tagom
ID: 36831847
Okay, can you be a little more specific than you don't need to that...I do not know what "that" is which does not need to be added and no I only want to pull a view of the table.

I apologize for being dense, but so much is left out in the email communications...I have a hard time with this and that as opposed to something like - you do not need to add...to your aspx file at this time.

0
 

Author Comment

by:Tagom
ID: 36837335
okay I figured it out
I now need to add the GridView1 asp label to the cs code as I am receiving the following error:
GridView1 does not exist  in the current context
0
 

Author Closing Comment

by:Tagom
ID: 36854861
was very patient with me!
0
 
LVL 6

Expert Comment

by:mjfagan
ID: 36855138
I'm not exactly sure what your error is from so I'm going to ask--did you click and drag a GridView control to your form?  By default, the first gridview on a form is named GridView1.
0
 

Author Comment

by:Tagom
ID: 36856775
I opened a related question and listed the error -
that way the points are better assessed...you have put quite a bit of time and patience in with me!
I have the gridview1 error fixed...starting to see how some of this is working...just rusty rusty!
here is the new question
http://www.experts-exchange.com/Programming/Languages/.NET/ASP.NET/Q_27367719.html
0

Featured Post

On Demand Webinar - Networking for the Cloud Era

This webinar discusses:
-Common barriers companies experience when moving to the cloud
-How SD-WAN changes the way we look at networks
-Best practices customers should employ moving forward with cloud migration
-What happens behind the scenes of SteelConnect’s one-click button

Question has a verified solution.

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

Having just graduated from college and entered the workforce, I don’t find myself always using the tools and programs I grew accustomed to over the past four years. However, there is one program I continually find myself reverting back to…R.   So …
This article is meant to give a basic understanding of how to use R Sweave as a way to merge LaTeX and R code seamlessly into one presentable document.
The viewer will learn how to clear a vector as well as how to detect empty vectors in C++.
In a recent question (https://www.experts-exchange.com/questions/29004105/Run-AutoHotkey-script-directly-from-Notepad.html) here at Experts Exchange, a member asked how to run an AutoHotkey script (.AHK) directly from Notepad++ (aka NPP). This video…

751 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