Blue Theme Orange Theme Green Theme Red Theme
 
Home | Forums | Videos | Photos | Blogs | Beginners
 | Consulting  
Submit an Article Submit a Blog 
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
 Resources  
Close
 Our Network  
Close
Search :       Advanced Search »
Home » ASP.NET and Web » Paging in ASP.NET using VB.NET

Paging in ASP.NET using VB.NET


This article explain Paging in ASP.NET web application.

Total page views :  15410
Total downloads : 
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
 
Become a Sponsor

Description 

Hello viewers, anybody in the Programming world would know that paging database results and its effect. The day from the beginning I started my asp journey my first bitter experience is writing a program and display the record set results with paging format. So at last I was successful in writing Program for this. When I started upgrading my self for ASP.Net my mind first went on paging program in ASP.Net so after experiencing the success on this task on ASP.Net here I am furnishing the code and I feel it is helpful to the people like me.

Now, if anyone has looked into the Microsoft .NET SDK and Quickstart samples you will find custom paging samples, but it's the usual next and previous stuff. Now let's see how we can kick this paging up a notch and tell us more detail about our data output

Accessing our Data

The first step is of course to query our database, and send our data into our datagrid. Import the Necessary Namespaces which are required like apps and sqlclient(for Ms-Sql Server). Here I have considered Pubs database in MS-Sql server-2000. This importing of namespaces is all done before our script tags like so:

<%@ Import Namespace = "System.Data" %>
<%@ Import Namespace = "System.Data.SqlClient" %>

Now, within our server-side script tags we include our object-oriented knowledge – our Subroutine to access our database and bind our result set to our ASP.NET Datagrid. This subroutine,  rs_bind_sql() creates all of our variables that we'll use:

 

Sub rs_bind_sql()        ' Begin Sub routine     

    Dim MyConnection As SqlConnection

    Dim DS As DataSet

    Dim MyCommand As SqlDataAdapter

    Dim RcdCount As Integer

    'SQL string

    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"

    'The connection to our database 

    Dim strConn As String = "server=(localsql);uid=sa;pwd=;" & _

    "database=Pubs;Trusted_Connection=yes;"

    'Next we need to instantiate our connection and command object, and the fill our DataSet 

    'object with the results of the SQL query: 

    '...  'Open up our connection with our connection object 

    MyConnection = New SqlConnection(strConn)

    'To execute our Sql Statement and provide our active connection 

    MyCommand = NewSqlDataAdapter(sqlStr, MyConnection)

    'Create instance of DataSet object and fill our predetermined 

    'datagrid with it and we    name it 

    DSet = New DataSet()

    MyCommand.Fill(DSet, "Pubs")

    'Now comes the one part that we'll used for our custom paging – the record count, and you'll see 

    'it quite different than our classic ASP way.  

    RcdCount = DSet.Tables("Pubs").Rows.Count.ToString()

    'Now that we have this total count of the records in the DataSet, we'll save it to a global 

    'variable, since we'll want to access it from other subroutines. The variable ResultCount 

    'should be defined in global-scope, as an Integer.  

    ResultCount = RcdCount

    'Next, we display the number of records found in a label control: 

    RecordCount.Text = "<b><font color=red>" & RcdCount & "</font> records found"

    'Finally, at this point, we can bind our DataSet to the DataGrid and display a label 

    'illustrating what page of results we're currently viewing: which will display :  

    Pubs.DataSource = DS  Pubs.Databind()   

    lblPageCount.Text = "Page " & Pubs.CurrentPageIndex + 1 & " of " & _    Pubs.PageCount  

    'At this point, we need to determine if we need to show the Next/Prev links, as well as the

    'First Page/Last Page links:

    'To Display Previous/Next Page Buttons  

    If Pubs.CurrentPageIndex <> 0 Then

        Call Prev_Buttons()

        Firstbutton.Visible = True

        Prevbutton.Visible = True

    Else

        Firstbutton.Visible = False

        Prevbutton.Visible = False

    End If

    'To Display Next/Last Page buttons  

    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

End Sub                'End Subroutine

 

That concludes our rs_bind_sql() subroutine.

HTML CODE

In this HTML version we need some label controls to be placed on the form to display information related such as the number/type of page we are viewing, the total records,number of records that are getting displayed etc., 

  • And also place a Datagridcontrol on the form  

  • Make sure The Datagrid is binding the database results

  • Finally, we need a series of LinkButton Web controls, to display our Prev/First Page and Next/Last Page links

The content for the HTML section is as follows:

<html>

<body>

    'For our recordcount and pagecount

    <asp:Label ID="lblPageCount" runat="server" /><br>

    <asp:Label ID="RecordCount" runat="server" />

    <form id="Form1" runat="server">

        <asp:DataGrid ID="Pubs" runat="server" AllowPaging="True" AllowCustomPaging="False"

            PageSize="10" PagerStyle-Visible="False" />

        <%-- Display the First Page/Previous Page buttons --%>

        <asp:LinkButton ID="Firstbutton" Text="<< 1st Page" CommandArgument="0" runat="server"

            OnClick="PagerButtonClick" />

        <asp:LinkButton ID="Prevbutton" Text="" CommandArgument="prev" runat="server"

            OnClick="PagerButtonClick" />

        <%-- Display the Next Page/Last Page buttons --%>

        <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 ID="Button1" Text="Change Pagesize" runat="server" OnClick="RePage" />

    </form>

</body>
</html> 

For DataGrid Web control we set the PagerStyle's Visible property to False. This is because we are implementing our own paging solution, and don't want to use the default paging style supported by the DataGrid Web control. (For more information on paging database results using the DataGrid's built-in functionality, be sure to read: Paging Database Results in ASP.NET!) Also note that the four LinkButton controls all specify the server-side subroutine PagerButtonClick as the sub to be called when they are clicked; similarly, the "Change Pagesize" button has the RePage subroutine defined as its OnClick event handler.

The event handler for the four LinkButtons (PagerButtonClick) must display the appropriate page of data, be it the next page, the previous page, the first page or the last page. Which page to display, of course, depends on what LinkButton the user clicks. The PagerButtonClick (shown below) uses the CommandArgument passed in from the LinkButton Web controls to determine which control was clicked, and then takes the appropriate action.

Protected Sub PagerButtonClick(ByVal sender As Object, ByVal e As System.EventArgs) Handles Lastbutton.Click, Firstbutton.Click, Prevbutton.Click, Nextbutton.Click

    'used by external paging UI                          

    Dim arg As String = sender.CommandArgument

    Select Case arg

        Case "next"

            'The next Button was Clicked

            If (Pubs.CurrentPageIndex < (Pubs.PageCount - 1)) Then

                Pubs.CurrentPageIndex += 1

            End If

        Case "prev"

            'The prev button was clicked

            If (Pubs.CurrentPageIndex > 0) Then

                Pubs.CurrentPageIndex -= 1

            End If

        Case "last"

            'The Last Page button was clicked 

            Pubs.CurrentPageIndex = (Pubs.PageCount - 1)

        Case Else

            'The First Page button was clicked

            Pubs.CurrentPageIndex = Convert.ToInt32(arg)

    End Select

    'Now, bind the data!

    rs_bind_sql()
End Sub

The RePage event handler, which is called when the "Change Pagesize" button is clicked, simply resets the DataGrid's CurrentPageIndex property back to 0 and rebinds the database data:

Protected Sub RePage(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click

    Pubs.CurrentPageIndex = 0

    rs_bind_sql()
End Sub

Finally, the last two server-side subroutines are two major helper subroutines, Next_Buttons() and Prev_Buttons(), which display the correct text for each of the LinkButtons. These two subs, which are called from rs_bind_sql(), can be seen below:

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

        EndCount = ResultCount - (Pubs.PageSize * (Pubs.CurrentPageIndex + 1))

        NextButton.Text = ("Next " & EndCount & " >")

    End If

End Sub


Login to add your contents and source code to this article
 About the author
 
Gopal
Looking for C# Consulting?
C# Consulting is founded in 2002 by the founders of C# Corner. Unlike a traditional consulting company, our consultants are well-known experts in .NET and many of them are MVPs, authors, and trainers. We specialize in Microsoft .NET development and utilize Agile Development and Extreme Programming practices to provide fast pace quick turnaround results. Our software development model is a mix of Agile Development, traditional SDLC, and Waterfall models.
Click here to learn more about C# Consulting.
 
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
Dynamic PDF
ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
SQL and .NET performance profiling in one place
Investigate SQL and .NET code side-by-side with ANTS Performance Profiler 6, so you can see which is causing the problem without switching tools.
Go.NET
Build custom interactive diagrams, network, workflow editors, flowcharts, or software design tools. Includes many predefined kinds of nodes, links, and basic shapes. Supports layers, scrolling, zooming, selection, drag-and-drop, clipboard, in-place editing, tooltips, grids, printing, overview window, palette. 100% implemented in C# as a managed .NET Control. Document/View/Tool architecture with many properties&events. Optional automatic layout.
Dundas Software
Dundas Chart for .NET is the most advanced .NET charting package available today.  With an extremely complete feature set, elegant architecture and easy implementation, Dundas Chart can quickly add advanced Charting functionality to enhance and transform ASP.NET and Windows Forms applications.  Whether you are implementing charting into internal projects, or building applications for clients, Dundas Chart offers advanced technology and advanced results to get the most out of data.
60 FREE UI Controls from DevExpress
Register for your FREE copy on over 60 free presentation controls from DevExpress - Absolutely Free-of-Charge without any royalties or distribution costs. Visit Devexpress.com/60 today. Free controls include advanced lists box, dropdown calendar, rich text edit, spin edit, tab control and so much more!

DevExpress engineers feature rich presentation controls and reporting tools for WinForms, ASP.NET, WPF, and Silverlight. Our technologies help you build your best, see complex software with greater clarity and deliver compelling business solutions for Windows and the web in the shortest possible time.
Clickatell's SMS Gateway
Clickatell's Developer Solutions allow you to SMS enable any website or application via a range of API's. Learn More about our API connections.
Free access to .NET Memory Management video
Everything you need to know about Garbage Collection, Temporary Objects, Fragmentation, Finalization and common causes of memory leaks in .NET. Watch the video here.
Microsoft Visual Studio 2010
Visualize your workspace with new multiple monitor support, powerful Web development, new SharePoint support with tons of templates and Web parts, and more accurate targeting of any version of the .NET Framework. Get set to unleash your creativity.
Nevron Chart for .NET 2010.1 Now Available
The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
Developer-Ready ASP.NET 2.0 Web Hosting with 3 MONTHS FREE
Now supporting .NET 3.0 Framework with Windows Workflow Foundation, Windows Communication Foundation (WCF), Windows Presentation Foundation (WPF), windows CardSpace (WCS)! Providing more flexibility for Developers with Web Services Support and a User/Permission Manger. Also supporting MS SQL 2005/2000 with Real-Time Backups, FREE Automated Attach .MDF Tool, FREE SQL Restore and Shrink SQL DB Tools, and SQL
Read the Top 10 Books for Microsoft Developers, 15 Days FREE
Read the Top 10 Books for Microsoft Developers, 15 Days FREE
Try Safari Books Online - 15 Days FREE + 15% Off for 1 Year
Try Safari Books Online - 15 Days FREE + 15% Off for 1 Year
 
 Post a Feedback, Comment, or Question about this article
Subject:
Comment:
Become a Sponsor
 Comments
Paging in ASP.NET using VB.NET by Bhim Rao On March 20, 2007
Hi Gopal I'm the Beginner (ASP.Net) This piece of information thrown light on many darkness.Thank u very much. Greatfull to U Gopal
Reply | Email | Delete | Modify | 
Code Download? by Helen On August 27, 2007
Is it possible to supply a sample code download for this example?
Reply | Email | Delete | Modify | 
ANTS Performance Profiler 6.0
 Hosted by MaximumASP  |  Found a broken link?  |  Contact Us  |  Terms & conditions  |  Privacy Policy  |  Site Map  |  Suggest an Idea  |  Media Kit
Current Version: 5.2010.8.14
 © 2010  contents copyright of their authors. Rest everything copyright Mindcracker. All rights reserved.