Solved

returning data to html page via datagrid

Posted on 2011-09-29
16
305 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
  • 9
  • 7
16 Comments
 
LVL 6

Accepted Solution

by:
mjfagan earned 500 total points
Comment Utility
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
Comment Utility
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
Comment Utility
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
 

Author Comment

by:Tagom
Comment Utility
do you by chance have an example of this.
0
 
LVL 6

Expert Comment

by:mjfagan
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
I really appreciate all of your help. I am obviously not getting it.
0
How to improve team productivity

Quip adds documents, spreadsheets, and tasklists to your Slack experience
- Elevate ideas to Quip docs
- Share Quip docs in Slack
- Get notified of changes to your docs
- Available on iOS/Android/Desktop/Web
- Online/Offline

 
LVL 6

Expert Comment

by:mjfagan
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
was very patient with me!
0
 
LVL 6

Expert Comment

by:mjfagan
Comment Utility
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
Comment Utility
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

How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

There is an easy way, in .NET, to centralize the treatment of all unexpected errors. First of all, instead of launching the application directly in a Form, you need first to write a Sub called Main, in a module. Then, set the Startup Object to th…
Whether you’re a college noob or a soon-to-be pro, these tips are sure to help you in your journey to becoming a programming ninja and stand out from the crowd.
The goal of this video is to provide viewers with basic examples to understand and use switch statements in the C programming language.
The viewer will learn how to user default arguments when defining functions. This method of defining functions will be contrasted with the non-default-argument of defining functions.

743 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

Need Help in Real-Time?

Connect with top rated Experts

18 Experts available now in Live!

Get 1:1 Help Now