Why my DataTables in DataSet are cleared?

K

Kevin.Li

I am using ASP.NET 2.0.

My DataTable in DataSet are cleared automatically!

The follow is my code:
//--------------- I just keep what core part related to the
problem-----------------------------------------
using System;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Web;
using System.Web.UI;

public partial class _Default : System.Web.UI.Page
{
DataTable ds = new DataSet();
string cs = "Data Source=.;Initial Catalog=Northwind;Integrated
Security=True";

protected void Button1_Click(object sender, EventArgs e)
{
string ss = "select
CompanyName,ContactName,ContactTitle,Country,HomePage,Fax,Phone from
Suppliers where "+ selColumn + " = '" + selValue+" ' ";
SqlDataAdapter sda = new SqlDataAdapter(ss,cs);
sda.Fill(ds,"suppliers"); // Everything works well here,
int test = ds.Tables.Count // test will be assigned to
1.
}
protected void btnFirst_Click(object sender, EventArgs e)
{

int test = ds.Tables.Count; // test is 0! Where did my
"suppliers" table gone?
if (ds.Tables["suppliers"].Rows.Count > 0) // Hence, exception:
NullReferenceException.
{
// to do something;
}
}

I still have reference in dataset to the datatable, how can the
datatable be released?

Please help me.. Thanks !
 
K

Kevin.Li

Are you clicking btnFirst without clicking on Button1 by mistake?

Kalpesh

Kalpesh,Thanks for your quick reply.

I was not clicking btnFirst without clicking on Button1 by mistake. I
had tested several times before asking for help.

I understand the reason now.

That was because:

When I click another button on the page, I 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 ds = new DataSet(); // When click the btnSave button,
dtData will be assigned to null.
...
...

}

Kalpesh , thanks again.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top