Question

I have a quite simple problem in ASP.NET, which I already encountered in different forms but I never found an answer to it.

The problem is that I want to do some calculations in response to a Postback event (e.g. OnClick event of a button), which I then want to show in a GridView with a DataObjectSource.

The problem is that the page life cicle wants to fill the DataObjectSource, before executing the OnClick event. I see why this order makes sense in general, but I don't know how I can change my code so that it works. Depending on whether I initialize the result variable, I either get a null Pointer exception or just an empty table.

Here some relevant parts of the code:

Page_Load() 
{
    GridView1.Visible = IsPostBack;
}

DataTable result;

Btn_Click()
{
    // do some calculations
    result = ...;
}

GetData()
{
    return result;
}

As GetData() is called before Btn_Click(), the table is empty (or even null here).

Was it helpful?

Solution

Using GridView.DataBind() method :

Page_Load() {
    GridView1.Visible = IsPostBack;
}

DataTable result;

Btn_Click() {
    // do some calculations
    result = ...;

    // calculations finished... bind the gridview
    GridView1.DataBind();
}

GetData() {
    return result;
}

This will re-bind the GridView to the datasource object once the calculations have been completed.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top