In this tutorial, learn how to dynamically load data in a GridView control on page scrolling using jQuery. This performance-enhancing technique loads records on demand, optimizing the user experience.
HTML Design
Create a div tag containing a GridView control inside, and set the div style property for overflow to auto. This ensures the GridView remains within a fixed height while allowing the scroll down feature.
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="GridviewLoadingData.WebForm1" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script src="Jscript/jquery-2.2.3.min.js"></script>
<script type="text/javascript">
//Add JQuery| Javascript Script Here
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<table class="Grid" cellspacing="0" rules="all" border="1" id="Table1" style="width: 400px; border-collapse: collapse;">
<tr>
<th scope="col" style="width: 200px;">Student Name</th>
<th scope="col" style="width: 200px;">Address</th>
</tr>
</table>
<div id="dvGrid" style="height: 150px; overflow: auto; width: 417px">
<asp:GridView ID="gvStudentInfo" runat="server" AutoGenerateColumns="false" CssClass="grid" Width="400">
<Columns>
<asp:BoundField DataField="Student_Name" HeaderText="Student Name" ItemStyle-Width="200" HeaderStyle-Width="200" />
<asp:BoundField DataField="Addres" HeaderText="Address" ItemStyle-Width="200" HeaderStyle-Width="200" />
</Columns>
</asp:GridView>
</div>
</div>
</form>
</body>
</html>
Database - Creating Stored Procedure
Implement a stored procedure with paging options to fetch records based on index and page count, enabling the loading of data on demand.
CREATE PROCEDURE GetStudentsPageWise
@PageIndex INT, @PageSize INT, @PageCount INT OUTPUT
AS
/*
pagging in procedure side
*/
BEGIN
SET NOCOUNT ON;
SELECT ROW_NUMBER() OVER ( ORDER BY [StudentID] ASC) AS RowNumber,
[StudentID],
[Student_Name],
[Addres]
INTO #Results
FROM StudentInfo;
DECLARE @RecordCount AS INT;
SELECT @RecordCount = COUNT(*)
FROM #Results;
SET @PageCount = CEILING(CAST (@RecordCount AS DECIMAL (10, 2)) / CAST (@PageSize AS DECIMAL (10, 2)));
SELECT *
FROM #Results
WHERE RowNumber BETWEEN (@PageIndex - 1) * @PageSize + 1 AND (((@PageIndex - 1) * @PageSize + 1) + @PageSize) - 1;
DROP TABLE #Results;
END
C# Coding - Add Namespaces
Include necessary C# namespaces for handling data operations.
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace GridviewLoadingData
{
public partial class WebForm1 : System.Web.UI.Page
{
}
}
C# Coding - Page Loading
Load initial data on page load to populate the GridView.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
gvStudentInfo.DataSource = GetStudentsPageWise(1, 10);
gvStudentInfo.DataBind();
}
}
C# Coding - Binding Gridview Control
Create a method to fetch records based on page index and page size.
public static DataSet GetStudentsPageWise(int pageIndex, int pageSize)
{
string constring = ConfigurationManager.ConnectionStrings["dbCon"].ConnectionString;
using (SqlConnection con = new SqlConnection(constring))
{
using (SqlCommand cmd = new SqlCommand("[GetStudentsPageWise]"))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@PageIndex", pageIndex);
cmd.Parameters.AddWithValue("@PageSize", pageSize);
cmd.Parameters.Add("@PageCount", SqlDbType.Int, 4).Direction = ParameterDirection.Output;
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.Connection = con;
sda.SelectCommand = cmd;
using (DataSet ds = new DataSet())
{
sda.Fill(ds, "Students");
DataTable dt = new DataTable("PageCount");
dt.Columns.Add("PageCount");
dt.Rows.Add();
dt.Rows[0][0] = cmd.Parameters["@PageCount"].Value;
ds.Tables.Add(dt);
return ds;
}
}
}
}
}
C# Coding - Create WebServices
Define a WebMethod to fetch students' data based on the page index.
[WebMethod]
public static string GetStudents(int pageIndex)
{
System.Threading.Thread.Sleep(2000);
return GetStudentsPageWise(pageIndex, 10).GetXml();
}
JQuery | JavaScript - Remove GridView Header
Use jQuery to remove the GridView default header, ensuring smooth scrolling without header interference.
$(function () {
//Remove the original GridView header
$("[id$=gvStudentInfo] tr").eq(0).remove();
});
Load Data in GridView while Scrolling
Implement the jQuery code to load data dynamically when scrolling down. This involves making AJAX calls to the WebMethod and appending the retrieved records to the GridView.
<script type="text/javascript" src="../1.8.3/jquery.min.js"></script>
<script type="text/javascript">
var pageIndex = 1;
var pageCount;
$(function () {
//Remove the original GridView header
$("[id$=gvStudentInfo] tr").eq(0).remove();
});
//Load GridView Rows when DIV is scrolled
$("#dvGrid").on("scroll", function (e) {
var $o = $(e.currentTarget);
if ($o[0].scrollHeight - $o.scrollTop() <= $o.outerHeight()) {
LoadRecords();
}
});
//Function to make AJAX call to the Web Method
function LoadRecords() {
pageIndex++;
if (pageIndex == 2 || pageIndex <= pageCount) {
//Show Loader
if ($("[id$=gvStudentInfo] .loader").length == 0) {
var row = $("[id$=gvStudentInfo] tr").eq(0).clone(true);
row.addClass("loader");
row.children().remove();
row.append('<td colspan = "999" style = "background-color:white"><img id="loader" alt="" src="loaderimage.gif" /></td>');
$("[id$=gvStudentInfo]").append(row);
}
$.ajax({
type: "POST",
url: "CS.aspx/GetStudents",
data: '{pageIndex: ' + pageIndex + '}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess,
failure: function (response) {
alert(response.d);
},
error: function (response) {
alert(response.d);
}
});
}
}
//Function to recieve XML response append rows to GridView
function OnSuccess(response) {
var xmlDoc = $.parseXML(response.d);
var xml = $(xmlDoc);
pageCount = parseInt(xml.find("PageCount").eq(0).find("PageCount").text());
var students = xml.find("Students");
$("[id$=gvStudentInfo] .loader").remove();
students.each(function (index) {
var student = $(this);
AppendNewRow ('[id$=gvStudentInfo]', '<tr><td>' + student.find("Student_Name").text() + '</td><td>' + student.find("Addres").text() + '</td></tr>');
});
//Hide Loader
$("#loader").hide();
}
function AppendNewRow(table, rowcontent) {
if ($(table).length > 0) {
if ($(table + ' > tbody').length == 0)
$(table).append('<tbody />');
($(table + ' > tr').length > 0) ? $(table).children('tbody:last').children('tr:last').append(rowcontent) : $(table).children('tbody:last').append(rowcontent);
}
}
</script>
0 Comments