Plunging into .NET Development

Weblog Pieter Gheysens
Microsoft .NET Development - C# - Enterprise Library - Visual Studio 2005 Team System - Compuware DevPartner - ...
 


Wednesday, November 1

ASP.NET 2.0 GridView - Paging without DataSourceControl

How to enable paging for a GridView without DataSourceControl?
  • Drag and drop a GridView on your webpage
  • Set property AllowPaging on GridView to true
  • Implement OnPageIndexChanging event in your code
  • Store datasource in a session object
  • Use session object for databinding in OnPageIndexChanging event

    protected void Page_Load(object sender, EventArgs e)

    {

        if (!Page.IsPostBack)

        {

            //load data from Database

            //this may only occur once (not in postback)

            CountryDataset ds = this.findData();

 

            //Add datatable to session

            Session["CountryDataSet"] = ds.Country;

 

            //Bind datatable to gridView

            this.GridView1.DataSource = ds.Country;

            this.GridView1.DataBind();

        }

    }

 

    protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)

    {

        //Load datatable from session

        this.GridView1.DataSource = (DataTable)Session["CountryDataSet"];

        //set new pageIndex

        this.GridView1.PageIndex = e.NewPageIndex;

        this.GridView1.DataBind();

    }

If you don't use the IsPostPack check, your data will be loaded each time from the database and so you won't need to store the datasource in a session object. But I prefer to store the data in memory to avoid extra database-calls. Another solution may be to store this data in a ViewState object instead of a session object : same results!

0 Comments:

Post a Comment

<< Home