confused by automatic object de-referencing

  • Thread starter Thread starter KavvY
  • Start date Start date
K

KavvY

Hi,

Considering the code posted below can anyone explain to me why the following
behaviour occurs?

On page load the testFillDataGrid() function gets called and the variable
sel is successfully set to reference an instance of SqlSelect. The rest of
the code displays a DataGrid using a DataView and the source sorted by the
criteria specified in the sortString.

It all works great at this point!

The problem occurs when clicking on the column headings of the DataGrid
which causes DataGrid1_SortCommand() to execute, this sets the variable
sortString and calls bindDataGrid().

At this point dv no longer references a DataView object, dv now references
nothing at all! In fact any class variables I created now happily reference
nothing!

I can't figure this out because I thought that class variables persisted
until either the page is closed, or I dereference them myself.

(ps - sorry about the indenting, oe is playing silly buggers)

Thanks
Rich.




namespace PhoneReports
{
/// <summary>
/// Summary description for Results.
/// </summary>
public class Results : System.Web.UI.Page
{

private string sortString = "Date";
private SqlSelect sel = new SqlSelect();
private DataView dv = new DataView();
private void Page_Load(object sender, System.EventArgs e)
{
// Put user code to initialize the page here
if (!IsPostBack)
{
testFillDataGrid();
}
}

private void testFillDataGrid()
{
string strSelect = "SELECT CONVERT(varchar(8),Date,5) AS Date, " +
"CONVERT(varchar(8),Time,8) AS Time, Country, [Number Dialled], " +
"Duration, Cost " +
"FROM [TBL Fixed Calls] " +
"WHERE [Billing Month] = '" + Session["month"].ToString() + "' " +
"AND [Account Number] = '" + Session["account"].ToString() + "' ";

sel = new SqlSelect(strSelect, component.sqlConn());
bindDataGrid();
}

private void bindDataGrid()
{
dv = new DataView(sel.getDataTable());
dv.Sort = sortString;
DataGrid1.DataSource = dv;
DataGrid1.DataBind();
}

private void DataGrid1_SortCommand(object source,
System.Web.UI.WebControls.DataGridSortCommandEventArgs e)
{
sortString = e.SortExpression;
bindDataGrid();
}
}
}
 
Hi,

Each time that you do a postback a NEW instance of the class ( page ) is
created, hence you have to REASSIGN your instance variables.
You can keep your datasource in session, then you do like this:

private void Page_Load(object sender, System.EventArgs e)
{
// Put user code to initialize the page here
if (!IsPostBack)
{
testFillDataGrid();
}
else
{
// recover data from cache/session
}
}


Cheers,
 
Back
Top