Implement custom paging in the ASP. NET DataGrid Control...

Source: Internet
Author: User
By: John kilgo Date: February 22,200 3 download the code. Printer friendly version

The inbuilt paging mechanism of the ASP. net DataGrid Control is convenient, but can be very inefficient. the problem with the inbuilt system is that the entire resultset is gathered again and again with each page change. assume you have a table with 200 rows in it and that you are displaying 10 rows at a time. everytime you change pages, all 200 rows are being returned again. the DataGrid then has to do the work of sorting out which 10 rows you want to see. as you deal with larger tables, the problem only gets worse.

With custom paging you can return only the 10 rows being requested each time the page is changed. this is much more efficient. you also have more options as to the style of the paging mechanism. there is nothing wrong with numericpages or nextprev, but sometimes I want to do something a little different. in this example, we will be accessing the northwind Products table, and our paging mechanisms will be implemented outside the DataGrid rather than within it. i'm not particle ly proud of the method I chose, but perhaps it will give you some ideas on other approaches. as usual we will employ An ASPX page for the DataGrid design and then do all the work in. VB code-behind file. first. ASPX page.

As you can see we have a very simple DataGrid design, setting only a few properties with most of them being cosmetic in nature. we do, however, set allowcustompaging to true. since we will be handling paging ourselves in code we don't need to set pagerstyle attributes or even set up an event for paging. below the DataGrid we have added two label controls to hold the current page number and the count of total pages. this is so we can display something like "page 3 of 8 ". below the labels we have created our own paging "control" using four buttons to allow paging to the first page, Previous Page, next page, and last page. I have used the poor man's version of VCR buttons. you cocould get fancy and use image buttons, Or you cocould just use text-based link buttons.

<% @ Page Language = "VB" src = "custpagedatagrid. aspx. VB" inherits = "dotnetjohn. custpagedatagrid" %>

<HTML>
<Head>
<Title> custpagedatagrid. aspx </title>
</Head>
<Body>
<Form runat = "server" id = "form1">
<Asp: DataGrid id = "dtgprod"
Allowcustompaging = "true"
Cellpadding = "4"
Runat = "server"
Bordercolor = "#898989"
Borderstyle = "NONE"
Borderwidth = "1px"
Backcolor = "white"
Gridlines = "vertical">

<Alternatingitemstyle backcolor = "# dcdcdc"/>
<Itemstyle forecolor = "black" backcolor = "# eeeeee"/>
<Headerstyle font-bold = "true" forecolor = "white" backcolor = "#000084"/>

</ASP: DataGrid>
<P>
Page
<Asp: Label id = "lblcurpage" runat = "server"/>
Of
<Asp: Label id = "lbltotpages" runat = "server"/>
</P>
<Asp: button id = "btnfirst"
Runat = "server"
TEXT = "| <"
Font-bold = "true"
Oncommand = "nav_onclick"
Commandname = "first"/>
<Asp: button id = "btnprev"
Runat = "server"
TEXT = "<"
Font-bold = "true"
Oncommand = "nav_onclick"
Commandname = "Prev"/>
<Asp: button id = "btnnext"
Runat = "server"
TEXT = ">"
Font-bold = "true"
Oncommand = "nav_onclick"
Commandname = "Next"/>
<Asp: button id = "btnlast"
Runat = "server"
TEXT = ">>|"
Font-bold = "true"
Oncommand = "nav_onclick"
Commandname = "last"/>
</Form>
</Body>
</Html>

And now for the code-behind page. in order to make it a little easier to see and discuss, we present the code-behind file in three sections. this first section is the top of the file down through the page_load sub routine. before getting to the code I shocould point out that the techniques used in this example program only work when there is an identity column in the table. if there is no identity table, you cocould write a stored procedure which creates a temporary table that does include an identity column, copy the Permanent Table into the temp table, and use the temp table to return results to the program.

The main purpose of the page_load routine is to determine the number of rows of data we will be dealing. we do a select count (*) from the table and then store the result in the DataGrid's virtualitemcount property. we then set our current page property (intcurpagenum) to 1 and call bindthegrid () to do the databinding.

Imports system
Imports system. Data
Imports system. Data. sqlclient
Imports system. Configuration

Namespace dotnetjohn

Public class custpagedatagrid: inherits system. Web. UI. Page

Protected dtgprod as system. Web. UI. webcontrols. DataGrid
Protected lblcurpage as system. Web. UI. webcontrols. Label
Protected lbltotpages as system. Web. UI. webcontrols. Label
Protected btnnext as system. Web. UI. webcontrols. Button
Protected btnprev as system. Web. UI. webcontrols. Button
Protected intcurpagenum as integer

Dim objconn as sqlconnection
Dim strselect as string
Dim intstartindex as integer
Dim intendindex as integer

Sub page_load (sender as object, e as eventargs)
Dim objcmd as sqlcommand

Objconn = new sqlconnection (configurationsettings. etettings ("connectionstring "))
If not ispostback then
'Get total rows
Strselect = "select count (*) from products"
Objcmd = new sqlcommand (strselect, objconn)
Objconn. open ()
Dtgprod. virtualitemcount = objcmd. executescalar ()
Objconn. Close ()
Intcurpagenum = 1
Bindthegrid ()
End if
End sub

Now for the "bindthegrid" sub-routine. in the upper part of the routine we use a paramaterized query to get the first 10 rows from the table. I say 10 rows because that is the value of dtgprod. pagesize. as you can see we are using a starting index (intstartindex) and an ending index (intendindex) to specify the range of rows we want from the table using the productid (identity column ). we then fill a dataset with the results of the query, and set our current page label (lblcurpage. text) to the current page number.

If this is the first time through the routine (not page. ispostback) we set a variable (inttotrecs) to hold the total number of rows we are dealing with in the table, and another variable (dectotpages) to the total number of pages (of 10 rows) we are dealing. the problem with this variable (dectotpages) is that it is equal to 7.7. to fix this display problem we using the system. math. ceiling function to "round up" to the nearest integer. that is so we can display "Page 1 of 8" rather than "Page 1 of 7.7 ".

In the last section of bindthegrid we test the value of intcurpagenum. if we are on the first page we want our previous page button to be disabled. if we are on the last page we want our next page button to be disabled. otherwise, both buttons shoshould be enabled.

Sub bindthegrid ()
Dim dataadapter as sqldataadapter
Dim dataset as Dataset

Intendindex = intstartindex + dtgprod. pagesize
Strselect = "select productid, productname, supplierid, categoryid ,"_
& "Unitprice, unitsinstock, discontinued "_
& "From products where productid> @ startindex "_
& "And productid <= @ endindex order by productid"
Dataadapter = new sqldataadapter (strselect, objconn)
Dataadapter. selectcommand. Parameters. Add ("@ startindex", intstartindex)
Dataadapter. selectcommand. Parameters. Add ("@ endindex", intendindex)
Dataset = new dataset
Dataadapter. Fill (Dataset)
Dtgprod. datasource = Dataset
Dtgprod. databind ()
Lblcurpage. Text = intcurpagenum. tostring ()

If not page. ispostback then
Dim inttotrecs as integer = CINT (dtgprod. virtualitemcount)
Dim dectotpages as decimal = decimal. parse (inttotrecs. tostring ()/dtgprod. pagesize
Lbltotpages. Text = (system. Math. Ceiling (double. parse (dectotpages. tostring (). tostring ()
End if

Select case intcurpagenum
Case 1
Btnprev. Enabled = false
Btnnext. Enabled = true
Case int32.parse (lbltotpages. Text)
Btnnext. Enabled = false
Btnprev. Enabled = true
Case else
Btnprev. Enabled = true
Btnnext. Enabled = true
End select
End sub

And now to complete the code-behind page. you may recall that on. ASPX page when we defined our page navigation buttons we have ded an oncommand method to raise the command event (nav_onclick ). it is here that we set the current page number (intcurpagenum) to be viewed. intcurpagenum is set as shown depending on which navigation button was clicked. we then set intstartindex (one of our SELECT statement parameters) to the current page number minus 1 times the DataGrid. pagesize propery. we then call bindthegrid () and we are done.

Sub nav_onclick (sender as object, e as system. Web. UI. webcontrols. commandeventargs)
Select case e. commandname
Case "first"
Intcurpagenum = 1
Case "last"
Intcurpagenum = int32.parse (lbltotpages. Text)
Case "Next"
Intcurpagenum = int32.parse (lblcurpage. Text) + 1
Case "Prev"
Intcurpagenum = int32.parse (lblcurpage. Text)-1
End select
Intstartindex = (intcurpagenum-1) * dtgprod. pagesize ()
Bindthegrid ()
End sub

End Class

End namespace

The code for custom paging can be a little tricky, but it does have efficiency advantages over the DataGrid's inbuilt paging mechanism. the larger the table you are dealing with the more you need paging. as the table grows larger you do not want to be returning the entire table in the resultset every time you change pages.

You may run the sample program here.
You may download the code here.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.