• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 374
  • Last Modified:

I need to return data from table to webpage

I have the aspx webpage collecting the data and storing it correctly. I have the aspx.cs page working correctly in the background.
It has been a long time since I have had to program in aspx I need some help with the returning of data.
ASPX page
<%@ 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">
<!-- TemplateBeginEditable name="doctitle" -->
	<title>Mercury Deposition Project</title>
	<meta name="description" content="Designed and developed by Codify Design Studio - codifydesign.com" />
	<!-- TemplateEndEditable -->
<link rel="stylesheet" type="text/css" href="stylesheet.css" />
		<script src="SpryAssets/SpryMenuBar.js" type="text/javascript"></script>
		<link href="SpryAssets/SpryMenuBarHorizontal.css" rel="stylesheet" type="text/css" />
		<!-- TemplateBeginEditable name="head" -->
		<!-- TemplateEndEditable -->
<body ms_positioning="GridLayout">

		<div class="bannerArea">
			<div class="container">
				<div class="bannernav"><a href="#" >Privacy Policy</a> &bull; <a href="#" >Contact Us</a> &bull; <a href="#" >Site Map</a></div>
				<div class="toplogo"><a href="index.htm" ><br/>Mercury Deposition Project</a><br/></div>
				<div style="clear:both;"></div>
<div class="topnavigationArea">
			<div class="container"> 
				<div class="topnavigationgroup">
					<ul id="MenuBar1" class="MenuBarHorizontal">
						<li><a class="MenuBarItemSubmenu" href="http://uwf.edu/hgdeposition/Publish/grantDetails.htm">Grant Details</a>
								<li><a href="http://uwf.edu/hgdeposition/Publish/methods.htm">Methods</a></li>
								<li><a href="http://uwf.edu/hgdeposition/Publish/localCollectionSites.htm">Local Collection Sites</a></li>
								<li><a href="http://uwf.edu/hgdeposition/Publish/regionalCollectionSites.htm">Regional Collection Sites</a></li>
                                <li><a href="http://uwf.edu/hgdeposition/Publish/photoJournal.htm">Photo Journal</a></li>
                                <li><a href="http://uwf.edu/hgdeposition/Publish/acknowledgements.htm">Acknowledgements</a></li>
						 <li><a class="MenuBarItemSubmenu" href="">Deliverables</a>
								<li><a href="http://uwf.edu/hgdeposition/Publish/conferences.htm">Conferences</a></li>
								<li><a href="http://uwf.edu/hgdeposition/Publish/publications.htm">Publications</a></li>
						<li><a class="MenuBarItemSubmenu" href="">Participants</a>
								<li><a href="http://uwf.edu/hgdeposition/Publish/janeCaffrey.htm">Dr. Jane Caffrey</a></li>
								<li><a href="http://uwf.edu/hgdeposition/Publish/sikhaBagui.htm">Dr. Sikha S. Bagui</a></li>
								<li><a href="http://uwf.edu/hgdeposition/Publish/suhashBagui.htm">Dr. Subhash C. Bagui</a></li>
								<li><a href="http://uwf.edu/hgdeposition/Publish/williamLanding.htm">Dr. William Landing</a></li>
                      <li><a class="MenuBarItemSubmenu" href="">DataBase</a>
								<li><a href="http://uwf.edu/hgdeposition/Publish/dataRequest.htm">Data Request</a></li>
										<li><a href="http://uwf.edu/hgdeposition/Publish/standardView.htm">Standard View</a></li>
                                        <li><a href="http://uwf.edu/hgdeposition/Publish/databaseDocumentation.htm">Database Documentation</a></li>
								<li><a href="uploadFiles">Upload Files</a></li>
										<li><a href="http://uwf.edu/hgdeposition/Publish/FSU.htm">FSU</a></li>
										<li><a href="http://uwf.edu/hgdeposition/Publish/UWF.htm">UWF</a></li>
								<li><a href="http://uwf.edu/hgdeposition/Publish/dataInput.htm">Data Input</a></li>
										<li><a href="http://uwf.edu/hgdeposition/Publish/rainEventsTable.htm">Rain Events Table</a></li>
										<li><a href="http://uwf.edu/hgdeposition/Publish/contaminationTable.htm">Contamination Table</a></li>

								<li><a href="http://uwf.edu/hgdeposition/Publish/dataCleaningConsiderations.htm">Data Cleaning Considerations</a></li>
                                <li><a href="http://uwf.edu/hgdeposition/Publish/dataMiningTechniques.htm">Data Mining Techniques</a></li>
                                <li><a href="http://uwf.edu/hgdeposition/Publish/challenges.htm">Challenges</a></li>
						<li style="border-right-style: solid;"><a href="http://uwf.edu/hgdeposition/Publish/sponsors.htm">Sponsors</a></li>
				<div style="clear:both;"></div>
		<div class="contentArea">
			<div class="container"><!-- TemplateBeginEditable name="content" -->
				<div class="contentleft">
    <form id="Form1" method="post" runat="server" enctype="multipart/form-data">
    <asp:Label ID="lab1" runat="server" Font-Bold="True">Please Select the Data File you will be uploading:</asp:Label>
    <br />
    <input id="filMyFile" type="file" runat="server">
    <asp:Label ID="notesLabel" runat="server" Font-Bold="True">Please give a description of the file you are uploading:<br /></asp:Label>
    <input id="lblnotes1" type="Text" runat="server">
    <br />
    <br />
    <asp:Button ID="cmdSend" runat="server" Text="Submit File to Database Folders" />
    <asp:Label ID="lblInfo" runat="server" Font-Bold="True" Visible="false"></asp:Label>
    <asp:Label ID="lblText1" runat="server" Font-Bold="True" Visible="True">This file will be placed in the FSU folder on the CEDB server.</asp:Label>
    <br />
    <br />
    <asp:Label ID="lblText2" runat="server" Font-Bold="True" Visible="True">This file and all of its meta data will be stored in uploadedData database</asp:Label>
    <asp:Image ID="imgFile" runat="server" Visible="False"></asp:Image> <br />
    <asp:Image ID="imgDB" runat="server" Visible="False"></asp:Image> <br />
			<!-- TemplateEndEditable --><!-- TemplateBeginEditable name="sidebar" -->
			<div class="contentright">
				<h2>The Center for Environmental Diagnostics and Bioremediation.</h2>
				<img src="images/uwf.jpg" width="103" height="105" border="0" class="imageright" />
<p>The Center for Environmental Diagnostics and Bioremediation
  (CEDB) reflects a fundamental emphasis on modern biological research as applied to environmental systems.</p>
<p>The Center for Environmental Diagnostics and Bioremediation at the   University of West Florida provides a vital program of research and   education.</p>
			<!-- TemplateEndEditable -->
			<div style="clear:both;"></div>
		<div class="footerArea">
			<div class="container"> 
				<div class="copyright">&copy; 2009 Our Company.  All rights reserved.</div>
		<script type="text/javascript">
		var MenuBar1 = new Spry.Widget.MenuBar("MenuBar1", {imgDown:"SpryAssets/SpryMenuBarDownHover.gif", imgRight:"SpryAssets/SpryMenuBarRightHover.gif"});

Open in new window

aspx.cs page
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";

        protected Label lblFile;
        protected HtmlInputFile filMyFile;
        protected System.Web.UI.WebControls.Label lblInfo;
        protected System.Web.UI.HtmlControls.HtmlInputText lblnotes1;
        protected System.Web.UI.WebControls.Button cmdSend;
        protected System.Web.UI.WebControls.Image imgFile;
        protected System.Web.UI.WebControls.Image imgDB;
        protected System.Web.UI.WebControls.Label lblText1;
        protected System.Web.UI.WebControls.Label lblText2;
        //protected System.Web.UI.WebControls.TextBox tbDate;
        //protected System.Web.UI.WebControls.TextBox tbTime;
        //protected System.Web.UI.WebControls.CheckBox complete;

        override protected void OnInit(EventArgs e)

        private void InitializeComponent()
            this.Load += new System.EventHandler(this.Page_Load);
            this.cmdSend.Click += new System.EventHandler(this.cmdSend_Click);

        private void Page_Load(object sender, System.EventArgs e)
            // Check if FileID was passed to this page as a parameter
            if (Request.QueryString["FileID"] != null)
                // Get the file out of database and return it to requesting client


        // Processes click on our cmdSend button
        private void cmdSend_Click(object sender, System.EventArgs e)
            // Check to see if file was uploaded
            if (filMyFile.PostedFile != null)
                // Get a reference to PostedFile object
                HttpPostedFile myFile = filMyFile.PostedFile;

                // Get size of uploaded file
                int nFileLen = myFile.ContentLength;

                // make sure the size of the file is > 0
                if (nFileLen > 0)
                    // Allocate a buffer for reading of the file
                    byte[] myData = new byte[nFileLen];

                    // Read uploaded file from the Stream
                    myFile.InputStream.Read(myData, 0, nFileLen);

                    // Create a name for the file to store
                    string strFilename = Path.GetFileName(myFile.FileName);

                    // Write data into a file
                    WriteToFile(Server.MapPath(@"FSU\" + strFilename), ref myData);

                    // Grab the dates, and put it into a datetime
                    //DateTime myDateTime = DateTime.Parse(tbDate.Text + " " + tbTime.Text);
                    // that gives you a true asp.net datetime, and you can format that
                    // however you like later....

                    // Store it in database
                    int nFileID = WriteToDB(strFilename, myFile.ContentType, ref myData, lblnotes1.Value);

                    // Set label's text
                    lblInfo.Text =
                        "Filename: " + strFilename + "<br>" +
                        "Size: " + nFileLen.ToString() + "<br>";

                    // Set URL of the the object to point to the file we've just saved
                    imgFile.ImageUrl = "File Name: " + " " + strFilename;
                    imgFile.ToolTip = "This file will be stored to the FSU folder as file.";
                    lblText1.Text = imgFile.ImageUrl;

                    // Set URL of the the object to point to the this script with ID of the file
                    // that will retrieve file out the database
                    imgDB.ImageUrl = "FileID = " + nFileID.ToString();
                    imgDB.ToolTip = "This file Will be stored in the uploadData database.";
                    lblText2.Text = imgDB.ImageUrl;

                    // show the images and text
                    imgFile.Visible = false;
                    imgDB.Visible = false;
                    lblText1.Visible = true;
                    lblText2.Visible = true;


        // Writes file to current folder
        private void WriteToFile(string strPath, ref byte[] Buffer)
            // Create a file
            FileStream newFile = new FileStream(strPath, FileMode.Create);

            // Write data to the file
            newFile.Write(Buffer, 0, Buffer.Length);

            // Close file

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

        // Writes file to the database
        private int WriteToDB(string strName, string strType, ref byte[] Buffer, string strNotes)
            int nFileID = 0;

            // Create connection
            OleDbConnection dbConn = new OleDbConnection(GetConnectionString());

            // Create Adapter
            OleDbDataAdapter dbAdapt = new OleDbDataAdapter("SELECT * FROM FSUdata", dbConn);

            // We need this to get an ID back from the database
            dbAdapt.MissingSchemaAction = MissingSchemaAction.AddWithKey;

            // Create and initialize CommandBuilder
            OleDbCommandBuilder dbCB = new OleDbCommandBuilder(dbAdapt);

            // Open Connection

            // New DataSet
            DataSet dbSet = new DataSet();

            // Populate DataSet with data
            dbAdapt.Fill(dbSet, "FSUdata");

            // Get reference to our table
            DataTable dbTable = dbSet.Tables["FSUdata"];

            // Create new row
            DataRow dbRow = dbTable.NewRow();

            // Store data in the row
            dbRow["FileName"] = strName;
            dbRow["FileSize"] = Buffer.Length;
            dbRow["ContentType"] = strType;
            dbRow["FileData"] = Buffer;
            dbRow["uploadDate"] = DateTime.Now;
            dbRow["Notes"] = strNotes;
            //dbRow["completeFile"] = checkedFile;
            //dbRow["dateGathered"] = myDateTime.Date.ToShortDateString();
            //dbRow["timeGathered"] = myDateTime.ToString("t");

            // Add row back to table

            // Update data source
            dbAdapt.Update(dbSet, "FSUdata");

            // Get newFileID
            if (!dbRow.IsNull("FileID"))
                nFileID = (int)dbRow["FileID"];

            // Close connection

            // Return FileID
            return nFileID;

        // Read file out of the database and returns it to client
        private void ShowTheFile(int FileID)
            // Define SQL select statement
            string SQL = "SELECT FileSize, FileData, ContentType, Notes FROM FSUdata WHERE FileID = "
                        + FileID.ToString();

            // Create Connection object
            OleDbConnection dbConn = new OleDbConnection(GetConnectionString());

            // Create Command Object
            OleDbCommand dbComm = new OleDbCommand(SQL, dbConn);

            // Open Connection

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

            // Read row

            // Clear Response buffer

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

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

            // Close database connection

            // End the page

        // 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

1 Solution
Hey Dude!

Have you tried with a text file? What is the behavior of the page when you submit a TXT, JPG, or HTML file? Returns nothing, blank page, error, ... ?

And are you SURE that you're getting it back right? If you want to test, you can upload a small TXT file, and do a Response.Write(byte[])dbRead["FileData"], 0, (int)dbRead["FileSize"]);
TagomAuthor Commented:
I am pretty sure that the data is being returned correctly:
But I also know that I do not have the code written correctly to return the data rows.
I know that it should be put in the .aspx page
I also need to be able to write the information out to a scv or txt file. Where would I put the Response.Write code to get the information returned correctly
the aspx page or the aspx.cs page...front end or back end?
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Cloud Class® Course: SQL Server Core 2016

This course will introduce you to SQL Server Core 2016, as well as teach you about SSMS, data tools, installation, server configuration, using Management Studio, and writing and executing queries.

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