473,320 Members | 2,164 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,320 software developers and data experts.

I lose data, when I try to save a loaded DataTable on the click ofanother button in an asp.net webform

Please can someone help me. I am writing a web application,
that allows for the upload of an excel sheet into the database.
I have an upload button and a save button.

The upload button allows for the retrieval of the excel data into
a DataTable, which is bound to a GridView for previewing before
saving to the Database.

But, whenever I click on the save button, I lose the DataTable's data,
so I lose the data I want to save to the database.

I am using .net framework 2.0, vs2005 professional, win xp
professional
and below is the codebehind file for the page.

Thanks in advance.

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using IConceptDBWebUpdate.BLL;

public partial class _Default : System.Web.UI.Page
{
DataTable dtData = null;

public string UploadID
{
get
{
return (ViewState["UploadID"] != null) ?
ViewState["UploadID"].ToString() : string.Empty;
}
set
{
ViewState["UploadID"] = value;
}
}

protected void Page_Load(object sender, EventArgs e)
{
//GridView1.DataSource =
IConceptDBWebUpdate.BLL.StockDetail.GetAllStockDet ails();
//GridView1.DataBind();
}
protected void Upload_Click(object sender, EventArgs e)
{
//DataTable dtData = null;
if (IsValid)
{
UploadID = Guid.NewGuid().ToString();
string path = string.Format("{0}\\{1}.xls",
ConfigurationManager.AppSettings["ExcelFilePath"], UploadID);

try
{

if (UploadExcel.PostedFile == null)
{
throw new Exception("Please select a File to
upload");
}
UploadExcel.PostedFile.SaveAs(path);
//Create query to be passed to the Excel conversion
method.
string sql = "Select * from [stockdetails$]";
//Store data from Excel file in a DataTable
dtData =
MicrosoftExcelClient.ConvertExcelToDataTable(path, sql);
//Bind the GridView to the DataTable to display the
data
GridView1.DataSource = dtData;
GridView1.DataBind();
//TODO: Delete all data in the current stockdetails
table
Upload.Visible = false;
btnSave.Visible = true;
//UploadExcel.Enabled = false;

}
catch (Exception ex)
{
Message.CssClass = "ErrorMessage";
string error = ex.Message.Replace("\n", "<br>");

Message.Text = String.Format("The following error
occured:<BR>{0}", error);
}
finally
{
System.IO.File.Delete(path);
}
}//End of IsValid check
}
protected void Cancel_Click(object sender, EventArgs e)
{

}


protected void btnSave_Click(object sender, EventArgs e)
{
//if (!Page.IsPostBack)
//{

//Loop through the DataTable and add the rows to the
Database table stockdetails.
foreach (DataRow row in dtData.Rows)
{
string company = row["company"].ToString();
string keyword = row["keyword"].ToString();
string stockprice = row["stockprice"].ToString();
string stockworth = row["stockworth"].ToString();
StockDetail.InsertStockDetails(company, keyword,
stockprice, stockworth);

}
//Database update complete.
Message.Text = String.Format("The Database has now been
updated.<BR>");

GridView1.Enabled = false;
//UploadExcel.Enabled = true;

//}//End of IsPostBack block
}
}
Dec 13 '07 #1
2 3008
hey, brother.

The reason you lost your datatable is that:

When you click another button on the page, you will generate *new*
request to the server, which means the code-behind will be re-
executed. therefore :
public partial class _Default : System.Web.UI.Page
{
int test = 0; // Set a break-point here, you
find out everything.
DataTable dtData = null; // When click the btnSave button,
dtData will be assigned to null.
...
...
}

//

Use session to store the dataset is a possible solution, however,
which I know is certainly not effient.

Does anyone have better solution.
Dec 13 '07 #2
The reason for this is that your instance is not maintained between
calls. You are better off getting the data source from the GridView1
(assuming that you are using viewstate, but that will be VERY expensive in
terms of how much data you are moving across the wire) and then working with
that on the save.

Or, you could store the data table in the session, and retrieve it when
saving.
--
- Nicholas Paldino [.NET/C# MVP]
- mv*@spam.guard.caspershouse.com

<ch*******@yahoo.comwrote in message
news:e9**********************************@i29g2000 prf.googlegroups.com...
Please can someone help me. I am writing a web application,
that allows for the upload of an excel sheet into the database.
I have an upload button and a save button.

The upload button allows for the retrieval of the excel data into
a DataTable, which is bound to a GridView for previewing before
saving to the Database.

But, whenever I click on the save button, I lose the DataTable's data,
so I lose the data I want to save to the database.

I am using .net framework 2.0, vs2005 professional, win xp
professional
and below is the codebehind file for the page.

Thanks in advance.

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using IConceptDBWebUpdate.BLL;

public partial class _Default : System.Web.UI.Page
{
DataTable dtData = null;

public string UploadID
{
get
{
return (ViewState["UploadID"] != null) ?
ViewState["UploadID"].ToString() : string.Empty;
}
set
{
ViewState["UploadID"] = value;
}
}

protected void Page_Load(object sender, EventArgs e)
{
//GridView1.DataSource =
IConceptDBWebUpdate.BLL.StockDetail.GetAllStockDet ails();
//GridView1.DataBind();
}
protected void Upload_Click(object sender, EventArgs e)
{
//DataTable dtData = null;
if (IsValid)
{
UploadID = Guid.NewGuid().ToString();
string path = string.Format("{0}\\{1}.xls",
ConfigurationManager.AppSettings["ExcelFilePath"], UploadID);

try
{

if (UploadExcel.PostedFile == null)
{
throw new Exception("Please select a File to
upload");
}
UploadExcel.PostedFile.SaveAs(path);
//Create query to be passed to the Excel conversion
method.
string sql = "Select * from [stockdetails$]";
//Store data from Excel file in a DataTable
dtData =
MicrosoftExcelClient.ConvertExcelToDataTable(path, sql);
//Bind the GridView to the DataTable to display the
data
GridView1.DataSource = dtData;
GridView1.DataBind();
//TODO: Delete all data in the current stockdetails
table
Upload.Visible = false;
btnSave.Visible = true;
//UploadExcel.Enabled = false;

}
catch (Exception ex)
{
Message.CssClass = "ErrorMessage";
string error = ex.Message.Replace("\n", "<br>");

Message.Text = String.Format("The following error
occured:<BR>{0}", error);
}
finally
{
System.IO.File.Delete(path);
}
}//End of IsValid check
}
protected void Cancel_Click(object sender, EventArgs e)
{

}


protected void btnSave_Click(object sender, EventArgs e)
{
//if (!Page.IsPostBack)
//{

//Loop through the DataTable and add the rows to the
Database table stockdetails.
foreach (DataRow row in dtData.Rows)
{
string company = row["company"].ToString();
string keyword = row["keyword"].ToString();
string stockprice = row["stockprice"].ToString();
string stockworth = row["stockworth"].ToString();
StockDetail.InsertStockDetails(company, keyword,
stockprice, stockworth);

}
//Database update complete.
Message.Text = String.Format("The Database has now been
updated.<BR>");

GridView1.Enabled = false;
//UploadExcel.Enabled = true;

//}//End of IsPostBack block
}
}
Dec 13 '07 #3

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
by: Mike L | last post by:
I'm open for any suggestions on how to better program this. I want the user to select a license from a combo box, cboPrivilege and then the user will click the add button, then a record will be...
3
by: Peter | last post by:
I have a webform on this form is a User Control and another webform in IFRAME On the User Control there is a save button. I want to click this button and somehow tell the webpage in IFRAME that...
5
by: Rod | last post by:
I've written 2 ASP.NET applications (I've worked on one with a team and another by myself). In my ASP.NET pages, when saving data to a backend database I've done it by using the click event of a...
6
by: Tejpal Garhwal | last post by:
I have datagrid filled with some data rows. At the run time i want know how many total rows are there in the data grid ? Any idea ? Any Suggestions ? Thanks in advance Tej
5
by: Aspnot | last post by:
Background: I have a data entry form that is bound to a DataSet. This DataSet contains 9 tables and the form displays data from each table in textboxes, not a DataGrid. One of the tables in the...
2
by: JaM | last post by:
Hi all, I have created a gridview vith dynamic textbox columns (they are in variable number, it depends on what things I select from database) aspx code:...
2
by: DubSport | last post by:
I have created a datatable in a function, and it is populated with data. I want to call a new function from an ASP button, and write out some of the values in the datatable, using: string...
0
by: svgeorge | last post by:
I have web pages for making several 9 type of payments. The data gets loaded on web page from SQL server 2005 database. Then I have Process payment button(ProcPaymBTM_Click) on the web page(Detail...
0
by: dalaimanoj | last post by:
Hi experts, I have a form in which there are 4 textboxes and few command buttons like New, View, Save, Delete. I want to insert the values entered in textboxes are to be stored in an Oracle...
0
by: DolphinDB | last post by:
The formulas of 101 quantitative trading alphas used by WorldQuant were presented in the paper 101 Formulaic Alphas. However, some formulas are complex, leading to challenges in calculation. Take...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
0
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.