-->

How to load gridview rows on demand from database through scrolling in ASP.NET

Introduction

In this post I am explain how to load gridview rows on demand from database through scrolling in ASP.NET.

Here i am writing this article to explain how to load gridview rows on demand from database through scrolling in ASP.NET. This is also call Endless paging. This concept helps us to bind any number of records to the GridView with no performance impact.

Steps :

Step - 1 : Create New Project.

Go to File > New > Project > Select asp.net web forms application > Entry Application Name > Click OK.

Step-2: Add a Database.

Go to Solution Explorer > Right Click on App_Data folder > Add > New item > Select SQL Server Database Under Data > Enter Database name > Add.

Step-3: Create table for fetch data.

Open Database > Right Click on Table > Add New Table > Add Columns > Save > Enter table name > Ok.
In this example, I have used one tables as below

Step-4: Add Entity Data Model.

Go to Solution Explorer > Right Click on Project name form Solution Explorer > Add > New item > Select ADO.net Entity Data Model under data > Enter model name > Add.
A popup window will come (Entity Data Model Wizard) > Select Generate from database > Next >
Chose your data connection > select your database > next > Select tables > enter Model Namespace > Finish.

Step-5: Add a Webpage and Design for Show Data in Endless Gridview

Go to Solution Explorer > Right Click on Project name form Solution Explorer > Add > New item > Select web form/ web form using master page under Web > Enter page name > Add.

HTML Code
    <h3>Load Gridview rows on demand from database through scrolling in ASP.NET</h3>
    <div style="height:30px;">
        <span id="LoadingPanel" style="color:red; font-weight:bold; display:none;">
            Please Wait...
        </span>
    </div>
    <div id="dvGrid" style="height:300px; overflow:auto;width:400px">
        <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false"
            CellSpacing="5" Width="95%">
            <Columns>
                <asp:BoundField HeaderText="ID" DataField="StateID" />
                <asp:BoundField HeaderText="Country" DataField="Country" />
                <asp:BoundField HeaderText="State" DataField="StateName" />
            </Columns>
        </asp:GridView>
        <br />
        <%-- Here i have added 2 hidden fields for store current page & total page no --%>
        <asp:HiddenField ID="hfPageIndex" runat="server" Value="1" />
        <asp:HiddenField ID="hfTotalPage" runat="server" Value="0" />
        <br />
    </div>
        
JS Code
Write this below js Code for load gridview rows on demand from database through scrolling.

             <script src="Scripts/jquery-1.7.1.js"></script>
            <script language="javascript">
                $(document).ready(function () {
                    $('#dvGrid').bind('scroll', function () {
                        if($(this).scrollTop() + $(this).innerHeight()>=$(this)[0].scrollHeight){
                            var pageIndex = parseInt($('#<%=hfPageIndex.ClientID%>').val());
                            var totalPage = parseInt($('#<%=hfTotalPage.ClientID%>').val());
                            if (pageIndex < totalPage) {
                                // this is for check more data is exist to populate or not
                                // this is for show loading...
                                $('#LoadingPanel').css('display', 'block');
                                pageIndex = pageIndex + 1;
                                $('#<%=hfPageIndex.ClientID%>').val(pageIndex.toString());
                                // Call function here for load more data
                                populateData(pageIndex);
                            }
                        }
                    })
                });

                function populateData(pageIndex) {
                    // populate data from database
                    $.ajax({
                        url: "Default.aspx/PopulateDataByJquery", 
                        data: "{pageNo: "+ pageIndex +", noOfRecord: 50}",
                        type: "POST",
                        dataType: "json",
                        contentType: "application/json; charset=utf-8",
                        success: OnSuccess,
                        error: onError
                    });
                }

                function OnSuccess(data) {
                    var d = data.d;
                    for (var i = 0; i < d.length; i++) {
                        var row = $('#<%=GridView1.ClientID%> tr').eq(1).clone(true); // here clone 2nd row on gridview
                        $("td:nth-child(1)", row).html(d[i].StateID);
                        $("td:nth-child(2)", row).html(d[i].Country);
                        $("td:nth-child(3)", row).html(d[i].StateName);
                        $('#<%=GridView1.ClientID%>').append(row); // This will Add to Existing Row
                    }
                    $('#LoadingPanel').css('display', 'none');
                }
                function onError(){
                    alert('Failed!');
                    $('#LoadingPanel').css('display', 'none');
                }

            </script>
        

Step-6: Write following code in Page_Load event for Show data in Gridview.


             protected void Page_Load(object sender, EventArgs e)
            {
                if (!IsPostBack)
                {
                    PopulateData(1, 50);
                }
            }
        
Here is the function...
            private void PopulateData(int pageIndex, int noOfRecord)
            {
                int pageCount = 0;
                int totalRecord = 0;
                using (MyDatabaseEntities dc = new MyDatabaseEntities())
                {
                    totalRecord = dc.StateDatas.Count();
                    List<StateData> data = new List<StateData>();
                    int skip = (pageIndex - 1) * noOfRecord;
                    data = dc.StateDatas.OrderBy(a => a.Country).ThenBy(a => a.StateName).Skip(skip).Take(noOfRecord).ToList();
                    GridView1.DataSource = data;
                    GridView1.DataBind();
                }
                if (totalRecord > 0 && noOfRecord > 0)
                {
                    pageCount = (totalRecord / noOfRecord) + ((totalRecord % noOfRecord) > 0 ? 1 : 0);
                    hfTotalPage.Value = pageCount.ToString();
                }
            }
        

Step-7: Write this function into your page code behind for called from Jquery Code.


             [WebMethod]
            public static List<StateData> PopulateDataByJquery(int pageNo, int noOfRecord)
            {
                System.Threading.Thread.Sleep(2000);
                using (MyDatabaseEntities dc = new MyDatabaseEntities())
                {
                    List<StateData> data = new List<StateData>();
                    int skip = (pageNo - 1) * noOfRecord;
                    data = dc.StateDatas.OrderBy(a => a.Country).ThenBy(a => a.StateName).Skip(skip).Take(noOfRecord).ToList();
                    return data;
                }
            }
        

Step-8: Run Application.



Related Post


Hello ! My name is Sourav Mondal. I am a software developer working in Microsoft .NET technologies since 2010.

I like to share my working experience, research and knowledge through my site.

I love developing applications in Microsoft Technologies including Asp.Net webforms, mvc, winforms, c#.net, sql server, entity framework, Ajax, Jquery, web api, web service and more.