473,769 Members | 4,018 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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.Configur ation;
using System.Collecti ons;
using System.Web;
using System.Web.Secu rity;
using System.Web.UI;
using System.Web.UI.W ebControls;
using System.Web.UI.W ebControls.WebP arts;
using System.Web.UI.H tmlControls;
using IConceptDBWebUp date.BLL;

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

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

protected void Page_Load(objec t sender, EventArgs e)
{
//GridView1.DataS ource =
IConceptDBWebUp date.BLL.StockD etail.GetAllSto ckDetails();
//GridView1.DataB ind();
}
protected void Upload_Click(ob ject sender, EventArgs e)
{
//DataTable dtData = null;
if (IsValid)
{
UploadID = Guid.NewGuid(). ToString();
string path = string.Format(" {0}\\{1}.xls",
ConfigurationMa nager.AppSettin gs["ExcelFileP ath"], UploadID);

try
{

if (UploadExcel.Po stedFile == null)
{
throw new Exception("Plea se select a File to
upload");
}
UploadExcel.Pos tedFile.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 =
MicrosoftExcelC lient.ConvertEx celToDataTable( path, sql);
//Bind the GridView to the DataTable to display the
data
GridView1.DataS ource = dtData;
GridView1.DataB ind();
//TODO: Delete all data in the current stockdetails
table
Upload.Visible = false;
btnSave.Visible = true;
//UploadExcel.Ena bled = false;

}
catch (Exception ex)
{
Message.CssClas s = "ErrorMessa ge";
string error = ex.Message.Repl ace("\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(ob ject sender, EventArgs e)
{

}


protected void btnSave_Click(o bject sender, EventArgs e)
{
//if (!Page.IsPostBa ck)
//{

//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.Ins ertStockDetails (company, keyword,
stockprice, stockworth);

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

GridView1.Enabl ed = false;
//UploadExcel.Ena bled = true;

//}//End of IsPostBack block
}
}
Dec 13 '07 #1
2 3030
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.P age
{
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.co m

<ch*******@yaho o.comwrote in message
news:e9******** *************** ***********@i29 g2000prf.google groups.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.Configur ation;
using System.Collecti ons;
using System.Web;
using System.Web.Secu rity;
using System.Web.UI;
using System.Web.UI.W ebControls;
using System.Web.UI.W ebControls.WebP arts;
using System.Web.UI.H tmlControls;
using IConceptDBWebUp date.BLL;

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

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

protected void Page_Load(objec t sender, EventArgs e)
{
//GridView1.DataS ource =
IConceptDBWebUp date.BLL.StockD etail.GetAllSto ckDetails();
//GridView1.DataB ind();
}
protected void Upload_Click(ob ject sender, EventArgs e)
{
//DataTable dtData = null;
if (IsValid)
{
UploadID = Guid.NewGuid(). ToString();
string path = string.Format(" {0}\\{1}.xls",
ConfigurationMa nager.AppSettin gs["ExcelFileP ath"], UploadID);

try
{

if (UploadExcel.Po stedFile == null)
{
throw new Exception("Plea se select a File to
upload");
}
UploadExcel.Pos tedFile.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 =
MicrosoftExcelC lient.ConvertEx celToDataTable( path, sql);
//Bind the GridView to the DataTable to display the
data
GridView1.DataS ource = dtData;
GridView1.DataB ind();
//TODO: Delete all data in the current stockdetails
table
Upload.Visible = false;
btnSave.Visible = true;
//UploadExcel.Ena bled = false;

}
catch (Exception ex)
{
Message.CssClas s = "ErrorMessa ge";
string error = ex.Message.Repl ace("\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(ob ject sender, EventArgs e)
{

}


protected void btnSave_Click(o bject sender, EventArgs e)
{
//if (!Page.IsPostBa ck)
//{

//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.Ins ertStockDetails (company, keyword,
stockprice, stockworth);

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

GridView1.Enabl ed = false;
//UploadExcel.Ena bled = 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
3007
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 added to the data grid. My current code is coming up with errors, dt and drv are unknown in the else part of the if statement. if (this.dgPrivileges.DataSource == null) {
3
5995
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 the button was clicked, how would I do that? (in other words I want to save the webform data in IFRAME when the save button is clicked) Peter
5
2119
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 button and just using the data during postback. Now, however, I've got a WebForm that I'll be working on, and it is going to collect more data than I have collected from the user in the past. I want to be able to attempt to save each part and if...
6
6705
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
3113
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 ParentTable and the rest are children. For Example: The form shows the Customer and their most recently added Contact (in textboxes, not in a DataGrid). When I click the Add button on the form, I enumerate through all of the DataTables in the...
2
5880
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: __________________________________________ <asp:GridView AutoGenerateColumns="false" ID="GridView2" Runat="server" <Columns>
2
3462
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 RowValue; RowValue = dt.Rows.ToString(); Response.Write(RowValue); Now when I run that code from within the same function that the datatable was populated from, it works.
0
1372
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 View)This is done. on clicking this button(ProcPaymBTM_Click) on (Detail View) all selected (checked) data columns needs displayed on another page (Review Data) In this page i click confirm payment button to insert selected data to the SQL Tables. I...
0
980
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 database table 'mst_users' when the Save button is clicked. I have declared the below variables in the form declaration section. Dim conn As New OleDb.OleDbConnection() Dim da As New OleDb.OleDbDataAdapter() Dim dc As New...
0
9579
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9419
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10201
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10035
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
9851
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
6662
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5438
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3949
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3553
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.