Scroll to view more content in the grid

 
When we have large amount of data to display on a page, generally we use paging to display the data to the end user.
The disadvantage of using paging approach is that the user is required to click to the next page. The user is then no longer thinking about what they are reading, but about how to get more to read.

The Continue scrolling is same as Facebook see more button at the bottom of the page when you move down to the page it automatically load the content at run time.

I am going to show how to load the data at run time when end user scroll down to the page.

On the default.aspx, put the following code

 
<asp:ScriptManager ID="sm1" runat="server">
        <Scripts>
            <asp:ScriptReference Path="~/Scripts/jquery-1.4.1.js" />
        </Scripts>
    </asp:ScriptManager>
    <h1 style="color: Green">
        Scroll to view more content in the grid</h1>
    <div id="divProducts" style="height:300px;overflow:auto">
        <asp:GridView ID="GridView1" runat="server" CellPadding="4" ForeColor="#333333" EnableViewState="false"
            GridLines="None">
            <AlternatingRowStyle BackColor="White" />
            <FooterStyle BackColor="#990000" Font-Bold="True" ForeColor="White" />
            <HeaderStyle CssClass="header" BackColor="#990000" Font-Bold="True" ForeColor="White" />
            <PagerStyle BackColor="#FFCC66" ForeColor="#333333" HorizontalAlign="Center" />
            <RowStyle BackColor="#FFFBD6" ForeColor="#333333" />
        </asp:GridView>
    </div>
    <div>
        <asp:Button runat="server" Text="Get More records" ID="btnGetMoreRecords"
            onclick="btnGetMoreRecords_Click" />
    </div>
    <div id="divProgress" style="margin-top: -50px;margin-left:150px;z-index:-999">
            <img src="loading.gif" width="100" height="100" alt="" />
    </div>
    <div>
        <asp:HiddenField runat="server" ID="hiddenLastProductID" />
    </div>

The button “btnGetMoreRecords” will be displayed to the user only when total no of records being displayed in the gridview reaches a limit.

using System;
using System.Web.UI;
using System.Data;
 
public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            NorthwndDB db = new NorthwndDB();
            //Fetch 14 records initially.
            DataSet dsProducts=db.GetProducts();
            //Bind data to gridview
            GridView1.DataSource = dsProducts;
            GridView1.DataBind();
        }
    }
    protected void btnGetMoreRecords_Click(object sender, EventArgs e)
    {
        NorthwndDB db = new NorthwndDB();
        //Fetch next 14 records after the last product id
        DataSet dsProducts = db.FetchNextProducts(Convert.ToInt32(hiddenLastProductID.Value), 14);
        //Bind data to gridview
        GridView1.DataSource = dsProducts;
        GridView1.DataBind();
    }
 
}

Now time to bind the new records in divProducts when we reach at lowest point of gridview. that will first detect if the scrollbar has reached to the end. If the scroll bar has reached to the end of the div, it will make an Ajax call to the async handler to fetch more records from the database and append it to the last row of the gridview.

var previousProductId = 0;
        //Max records to display at a time in the grid.
        var maxRecordsToDisplay = 30;
 
        $(document).ready(function () {
 
            //initially hide the loading gif
            $("#divProgress").hide();
 
            //initially hide the button
            $("#btnGetMoreRecords").hide();
 
            //Attach function to the scroll event of the div
            $("#divProducts").scroll(function () {
                var scrolltop = $('#divProducts').attr('scrollTop');
                var scrollheight = $('#divProducts').attr('scrollHeight');
                var windowheight = $('#divProducts').attr('clientHeight');
                var scrolloffset = 20;
                if (scrolltop >= (scrollheight - (windowheight + scrolloffset))) {
 
                    //User has scrolled to the end of the grid. Load new data..
                    $("#divProgress").ajaxStart(function () {
                        $(this).show();
                    });
                    $("#divProgress").ajaxStop(function () {
                        $(this).hide();
                    });
                    BindNewData();
 
                }
            });
 
        });

ClientHeight

Returns the height of the visible area for an object, in pixels. The value contains the height with the padding, but it does not include the scrollBar, border, and the margin.
So if the difference between scrollHeight and clientheight is equal to the scrolltop value, we can say that scrollbar has reached to its end. We have optionally taken an offest value of 20 so as load content as soon as scroll bar is going to reach its end.

function BindNewData() {
 
            var lastProductId = $("#GridView1 tr:last").children("td:first").html();
 
            //get last table row in order to append the new products
            var lastRow = $("#GridView1 tr:last");
 
            //Fetch records only when the no. of records displayed in the grid are less than limit.
            if (GetRowsCount() < maxRecordsToDisplay) {
                if (parseInt(lastProductId, 10) > parseInt(previousProductId, 10)) {
                    previousProductId = lastProductId;
 
                    $.post("FetchRecordsHandler.ashx?lastProductId=" + lastProductId, function (data) {
                        if (data != null) {
                            //append new products rows to last row in the gridview.
                            lastRow.after(data);
                        }
                    });
                }
            }
            else {
 
                //Set value of last product id in hidden field so that we can access it from code behind.
                $("#hiddenLastProductID").val(lastProductId);
                //Check If there is more records in the database
                if (parseInt(lastProductId, 10) > parseInt(previousProductId, 10))
                    $("#btnGetMoreRecords").show();
            }
 
 
        }

The code for the handler is as follows:

<%@ WebHandler Language="C#" Class="FetchRecordsHandler" %>
 
using System;
using System.Web;
using System.Data;
using System.Text;
 
public class FetchRecordsHandler : IHttpHandler
{
 
    public void ProcessRequest(HttpContext context)
    {
        //Delay to create loading effect.
        System.Threading.Thread.Sleep(500);
 
        int lastProductId = Convert.ToInt32(context.Request.QueryString["lastProductId"]);
 
        context.Response.Write(GetProductsRows(lastProductId));
 
    }
    private string GetProductsRows(int lastProductId)
    {
        //Fetch records from the DB
        NorthwndDB db = new NorthwndDB();
        DataTable dtProducts = db.FetchNextProducts(lastProductId,4).Tables[0];
 
        StringBuilder sb = new StringBuilder();
        System.Data.DataRow rowProduct;
        if (dtProducts.Rows.Count > 0)
        {
            for (int rowIndex = 0; rowIndex < dtProducts.Rows.Count; rowIndex++)
            {
                //The below logic is for applying alternate row style
                if (rowIndex % 2 != 0)
                    sb.Append("<tr>");
                else
                    sb.Append("<tr style='color:#333333;background-color:#FFFBD6;'>");
 
                rowProduct = dtProducts.Rows[rowIndex];
                for (int j = 0; j < dtProducts.Columns.Count; j++)
                {
                    sb.Append("<td>" + rowProduct[j] + "</td>");
                }
                sb.Append("</tr>");
            }
        }
        return sb.ToString();
    }
    public bool IsReusable
    {
        get
        {
            return false;
        }
    }
 
}

Screen short of Loading records:

Author: Pavan

I am asp.net developer have good knowledge of Asp.net ver 05,08,10 and good hand in sql server.Proficient in Object Oriented Programming and javascript, jQuery. Achievements - Integrate Spotfire, appnexus API ASP.net with sql server. Hobbies - Blogging ,Games, Movies ,Teaching,Keeping myself update with new technologies

2 thoughts on “Scroll to view more content in the grid”

  1. Thanks Hirendra.It really helps to people who is looking for avoid paging and end user also happy to see large number of records by scroll down.

Comments are closed.