Round trip database reads becomes an issue with large databases. You may notice this occurs in grid views. Each time the dataset is sorted or filtered, the default grid view needs to be data binded. In most cases, the data source is the database (sql statement or stored procedure). An easy way to prevent these round trips across page loads is to use a session variable. One important aspect to note is that session variables expire by default after fifteen minutes.

We are going to store a Boolean variable rememberMe in a ViewState. By storing the Boolean in a ViewState, rememberMe will retain its value across page loads. In this example, the boolean variable rememberMe will default to false. The variable rememberMe can be read to and from as if any public class variable.

public partial class _Default : System.Web.UI.Page

{

  public bool rememberMe

  {

    get

    {

      object o = ViewState["rememberMe "];

      return (o == null)? false : (bool)o;

    }

    set

    {

      ViewState["rememberMe"] = value;

    }

  }  protected void Page_Load(object sender, EventArgs e)

  {

  }

}

Again, it is important to note that session variables expire by default after fifteen minutes. If a default value is not assigned, additional logic is required to prevent unanticipated affects. This method is very effective when retrieving an extremely large number of records. You will immediately notice the first query will take the standard query time, but each subsequent action on the same dataset will be very quick.

This entry was posted on Wednesday, March 12th, 2008 at 1:58 am and is filed under C#, Visual Studio. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.

Leave a Reply