Library tutorials & articles

Custom ASP.NET Datagrid Paging With Exact Count

The Source Code

<%@ Import Namespace = "System.Data" %>
<%@ Import Namespace = "System.Data.SQLClient" %>
<html><body>
<script language="VB" runat="server">
Sub Page_Load(sender As Object, e As EventArgs)
' Only bind the data on the first visit to the page
If Not Page.IsPostBack
    BindSQL()
End If
End Sub
'Create an variable in Global scope
Dim ResultCount as Integer

Sub BindSQL()
Dim MyConnection As SqlConnection
Dim DS as Dataset
Dim MyCommand As SqlDataAdapter
Dim sqlStr As String = "SELECT titles.title, authors.au_lname, authors.au_fname, titles.price FROM authors INNER JOIN titleauthor ON authors.au_id = titleauthor.au_id INNER JOIN titles ON titleauthor.title_id = titles.title_id"
Dim strConn As String = "server=(local);uid=sa;pwd=;database=pubs;Trusted_Connection=yes;"
Dim RcdCount As Integer
'Open up our connection with our connection object
MyConnection = New SQLConnection(strConn)
'To execute our Sql Statement and provide out active connection
MyCommand = New SqlDataAdapter(sqlStr, MyConnection)
'Create instance of dataset object and fill our predetermined datagrid with it and we name it
DS = new Dataset()
MyCommand.Fill(DS, "pubs")
RcdCount = DS.Tables("pubs").Rows.Count.ToString()
Pubs.Pagesize = CInt(ps.SelectedItem.Value)
If Not Page.IsPostback
    Pubs.CurrentPageIndex = 0
End if
ResultCount = RcdCount
RecordCount.Text = "<b><font color=red>" & RcdCount & "</font> records found"
'Now we assign the dataview to the datasource of the datagrid and we send it right on it
Try
    Pubs.DataSource = DS
    Pubs.Databind()
Catch e As Exception
    Pubs.CurrentPageIndex = 0
End Try
If Pubs.CurrentPageIndex <> 0 Then
    Call Prev_Buttons()
    Firstbutton.Visible = true
    Prevbutton.Visible = true
else
    Firstbutton.Visible = false
    Prevbutton.Visible = false
end if
If Pubs.CurrentPageIndex <> (Pubs.PageCount-1) then
    Call Next_Buttons()
    NextButton.Visible = true
    Lastbutton.Visible = true
else
    NextButton.Visible = false
    Lastbutton.Visible = False
end if
lblPageCount.Text = "Page " & Pubs.CurrentPageIndex + 1 & " of " & Pubs.PageCount
End Sub

Sub PagerButtonClick(sender As Object, e As EventArgs)
'used by external paging UI
Dim arg As String = sender.CommandArgument
Select arg
    Case "next":
    If (Pubs.CurrentPageIndex < (Pubs.PageCount - 1)) Then
        Pubs.CurrentPageIndex += 1
    End If
    Case "prev":
    If (Pubs.CurrentPageIndex > 0) Then
        Pubs.CurrentPageIndex -= 1
    End If
    Case "last":
    Pubs.CurrentPageIndex = (Pubs.PageCount - 1)
    Case Else:
    Pubs.CurrentPageIndex = Convert.ToInt32(arg)
End Select
BindSQL()
End Sub

Sub Prev_Buttons()
Dim PrevSet As String
If Pubs.CurrentPageIndex+1 <> 1 and ResultCount <> -1 Then
    PrevSet = Pubs.PageSize
    PrevButton.Text = ("< Prev " & PrevSet)

    If Pubs.CurrentPageIndex+1 = Pubs.PageCount Then
    FirstButton.Text = ("<< 1st Page")
    End If
End If
End Sub

Sub Next_Buttons()
Dim NextSet As String
If Pubs.CurrentPageIndex+1 < Pubs.PageCount Then
    NextSet = Pubs.PageSize
    NextButton.Text = ("Next " & NextSet & " >")
End If
If Pubs.CurrentPageIndex+1 = Pubs.PageCount-1 Then
    Dim EndCount As Integer = ResultCount - (Pubs.PageSize * (Pubs.CurrentPageIndex+1))
    NextButton.Text = ("Next " & EndCount & " >")
End If
End Sub

Sub Repage(sender As Object, e As EventArgs)
Pubs.CurrentPageIndex = 0
BindSQL()
End Sub
</script>

<asp:Label id="lblPageCount" runat="server" /><br>
<asp:label id="RecordCount" runat="server" />
<form runat="server">
    <ASP:Datagrid id="Pubs" runat="server"
            AllowPaging="True"
            AllowCustomPaging="False"
            PagerStyle-Visible = "False"
            HeaderStyle-BackColor="Blue"
            HeaderStyle-ForeColor="White"
    />
    <asp:linkbutton id="Firstbutton" Text="<< 1st Page" CommandArgument="0" runat="server" onClick="PagerButtonClick"/>
    <asp:linkbutton id="Prevbutton" Text= "" CommandArgument="prev" runat="server" onClick="PagerButtonClick"/>
      
    <asp:linkbutton id="Nextbutton" Text= "" CommandArgument="next" runat="server" onClick="PagerButtonClick"/>
    <asp:linkbutton id="Lastbutton" Text="Last Page >>" CommandArgument="last" runat="server" onClick="PagerButtonClick"/>
    <br><br><br><br>
    Change Pagesize
    <asp:DropDownList id="ps" runat="server">
    <asp:ListItem>4</asp:ListItem>
    <asp:ListItem>5</asp:ListItem>
    <asp:ListItem>7</asp:ListItem>
    <asp:ListItem selected>10</asp:ListItem>
    <asp:ListItem>12</asp:ListItem>
    <asp:ListItem>15</asp:ListItem>
    <asp:ListItem>22</asp:ListItem>
    </asp:DropDownList>
   
    <asp:button text="Change Pagesize" runat="server" OnClick="RePage"/>
</form>
</body>
</html>

This article was originally published on 4guysfromrolla.com.

Comments

  1. 08 Jul 2005 at 17:18

    Hi, thanks, I appreciate your compliments.


    I have written another older article that I think should help. It's entitled- Drilldown Datagrid Searching with ASP.NET.


    This article demonstrates how to do a standard search, display the results in a datagrid, then further filter and search the datagrid itself and drilldown into the datagrid results themselves.


    So to merge the two, work off of the aforementioned article and incorporate the custom paging. All this should be no problem, and plenty to get you up and running.


    Also, for scalability purposes, read another article of mine here on DF - .NET Data Caching . Between the two you'll be able to provide some great functionality and performance.


    I hope this helps!


    - Jimmy Markatos

  2. 08 Jul 2005 at 15:56

    I loved your article on custom paging but would very much like to know how to apply it when you filter your initial data set to retreive specific records. I have a grid with 813 records sorted by user name. I have a search box in which a user can enter a name in order to filter the original dataset. If the search result in only 4 pages of records how can I page through that new set of records? Thanks in advance for any help and for the great article.

  3. 26 Oct 2003 at 20:00

    Check this site...


    I too was on the same quest and I've created a best practices reference site that covers many enterprise topics necessary to create large scale enterprise sites.

  4. 17 Oct 2003 at 05:38
    Hello,

    Tankete, I just have try what you are asking for a couple of days ago :

    The principe is simple : returning only a needed page from 50th to 60th records consists in querying this way :

    SELECT * TOP 60 ... WHERE NOT IN SELECT TOP 50 * WHERE [joining primarykeys]

    I have taken advices from Dino Esposito's MSDN articles, and have created a PageQuery function thats returns such a SQL statement, based on a normal SQL statement, primaryKey information, currentpageindex and pagesize.

    This sample of code uses a custompaged enabled datagrid called dg, with a access database that contains a "HugeTable" table with a "ID" primary key.

    Do not forget to enable custompaging to your datagrid

    Code:


       Private _Cx As OleDbConnection

       Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

           _Cx = New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Password="""";User ID=Admin;Data Source=C:\Inetpub\wwwroot\labo\app\db\paged_datagrid.mdb;Mode=Share Deny None;")

           If Not IsPostBack Then
               dg.DataBind()
               DataList1.DataBind()
           End If

       End Sub

       '

       Private Sub dg_DataBinding(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles dg.DataBinding

           Dim sqlstr As String = PageQuery("SELECT * FROM HugeTable ORDER BY ID", "ID", dg.CurrentPageIndex, dg.PageSize)
           _Cx.Open()

           dg.VirtualItemCount = New OleDbCommand("SELECT COUNT(*) FROM HugeTable", _Cx).ExecuteScalar
           Dim dr As OleDbDataReader = New OleDbCommand(sqlstr, _Cx).ExecuteReader(CommandBehavior.CloseConnection)
           dg.DataSource = dr

       End Sub

       '
       '
       Private Function PageQuery(ByVal commandText As String, _
                                  ByVal primaryKey As String, _
                                  ByVal currentPageIndex As Integer, _
                                  ByVal pageSize As Integer) As String

           Dim SubQuery1_TopCount As Integer = IIf(currentPageIndex = 0, _
                                                   pageSize, _
                                                   currentPageIndex * pageSize + pageSize)

           Dim SubQuery1 As String = Replace(commandText, _
                                             "SELECT ", _
                                             String.Format("SELECT TOP {0} ", SubQuery1_TopCount))

           If currentPageIndex = 0 Then Return SubQuery1

           SubQuery1 = String.Format("({0}) AS T1", SubQuery1)

           Dim SubQuery2_TopCount As Integer = currentPageIndex * pageSize

           Dim SubQuery2 As String = Replace(commandText, _
                                             "SELECT ", _
                                             String.Format("SELECT TOP {0} ", SubQuery2_TopCount))

           SubQuery2 = String.Format("({0}) AS T2", SubQuery2)

           Dim MainQuery As String = String.Format("SELECT t1.* FROM {0} LEFT JOIN {1} ON T1.{2}= T2.{2} WHERE T2.{2} IS NULL", _
                                                   SubQuery1, _
                                                   SubQuery2, _
                                                   primaryKey)

           Return MainQuery

       End Function

       '

       Private Sub dg_PageIndexChanged(ByVal source As System.Object, ByVal e As System.Web.UI.WebControls.DataGridPageChangedEventArgs) Handles dg.PageIndexChanged
           dg.CurrentPageIndex = e.NewPageIndex
           dg.DataBind()
       End Sub



    Hope it helps. For SQL server, the built query could be better implemented using subqueries instead of inner join, which is much more faster in access.

    Laurent.
  5. 16 Oct 2003 at 14:58
    I was hoping that you would address how to do paging with exact counts while NOT returning the entire dataset from the database, just the current page worth of data. Can you provide any information on how you would accomplish that? The current approach that I can think of does not perform as well as desired.
  6. 01 Jan 1999 at 00:00

    This thread is for discussions of Custom ASP.NET Datagrid Paging With Exact Count.

Leave a comment

Sign in or Join us (it's free).

Dimitrios Markatos Dimitrios, or Jimmy as his friends call him, is a .NET developer/architect who specializes in Microsoft Technologies for creating high-performance and scalable data-driven enterprise Web and deskto...

Related podcasts

Events coming up

  • Mar 15

    DevWeek 2010

    London, United Kingdom

    DevWeek is Europe’s leading independent conference for software developers, database professionals and IT architects, and features expert speakers on a wide range of topics, including .NET 4.0, Silverlight 3, WCF 4, Visual Studio 2010, REST, Windows Workflow 4, Thread Synchronization, ASP.NET 4.0, SQL Server 2008 R2, LINQ, Unit Testing, CLR & C# 4.0, .NET Patterns, WPF 4, F#, Windows Azure, ADO.NET, Entity Framework, Debugging, T-SQL Tips & Tricks, and more.

Want to stay in touch with what's going on? Follow us on twitter!