Question

I'm new in ASP.Net, and I have a doubt about how things work around the DataBind:

  • Page_Load: if IsPostBack=false, I load my DataTable var (declared outside the Page_Load) and bind it to the GridView. My idea here was to preserve the DataTable, avoiding new queries to the database.

  • When I clicked on a different page, the PageIndexChanging was raised, doing this:

    protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        GridView1.PageIndex = e.NewPageIndex;
        GridView1.DataSource = _table;
        GridView1.DataBind();
    }
    
  • This didn't worked well, since the grid was shown empty. I found in other examples that the data source was completely reloaded, so I put the load code in a function, and changed my PageIndexChanging event:

    protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        GridView1.PageIndex = e.NewPageIndex;
        LoadData();
        GridView1.DataSource = _table;
        GridView1.DataBind();
    }
    
  • Not it worked like a charm! I understand that my DataTable was cleared between the Page_Load and the PageIndexChanging events, probably because the data table var was not retained by the server (remember I'm a newbie at ASP.NET...), but I would like to understand:

    1. Why the server does not retains the variable?
    2. There is a way to bypass this situation in order to avoid multiple server data requests? What are the pros & cons in the bypass?

Thanks a lot!

Was it helpful?

Solution

The server doesn't retain the value because each request is handled by a new instance of the page class. The variable holding the data table is not the same as the variable in the previous request.

You can avoid the database call if you store the data table somewhere between requests, but the drawback is the resources needed for that. If you put the data table in view state, it will cost you net bandwith and affect the page load time. If you store it on the server it adds to the memory used, and it's not trivial to keep track of what data you can remove from memory.

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