Implement Custom Paging In The ASP.NET DATAGRID CONTROL ...

xiaoxiao2021-03-06  68

By: John Kilgo Date: February 22, 2003 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 mechanism will be implemented outside the datagrid rather than within it. I'm not particularly proud of the method I chose, but .................. ..

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 do not 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 could get fancy and use Image buttons, or you could just use text-based link button.

<% @ Page language = "VB" src = "CustPageDataGrid.aspx.vb" inherits = "DotNetjohn.custPageDataGrid"%> CUSTPAGEDATAGRID.ASPX </ title> </ head> <body> <form runat = "server" id = "form1"> <ask: 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" /> </ ask: DataGrid> <p> Page <ask: label id = "lblcurpage" runat = "server" /> of <ask: 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" /> <ask: button id = "btnnext" runat = "</p> <p>Server "text ="> "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "",, ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,, = "True" oncommand = "nav_onclick" commandName = "last" /> </ form> </ body> </ html> and now for the code-behind page. In Order To make it it is 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 should 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 could write a stored procedure which creates a temporary table that does include an identity column, copy the permanent table into the the temp table, and use the temp table to return results to The Program.</p> <p>The main purpose of the Page_Load routine is to determine the number of rows of data we will be dealing with. 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 data.</p> <p>Imports SystemImports System.DataImports System.Data.SqlClientImports System.ConfigurationNamespace DotNetJohnPublic 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.AppSettings ( "ConnectionString")) If Not IsPostBack Then 'Get Total Rows strSelect = "Select Count (*) From Products "objcmd = new sqlcommand (strsyct, objconn) objconn.open () dTGProd.VirtualItemcount = objcmd.executescalar () Objconn .Close () intCurPageNum = 1 BindTheGrid () End If End SubNow 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 setur current page label (lblcurpage.text) to the current page number.</p> <p>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 with. 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 Should Be enabled.</p> <p>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 ()) / DTGPROD.PAGESIZE LBLTOTPAGES.TEXT = (System.math.ceiling (Double.Pars) otPages.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 SUB</p> <p>And now to complete the code-behind page. You may recall that on the .aspx page when we defined our page navigation buttons we included 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 Subend Classend Namespace</p> <p>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.</p> <p>You May Run The Sample Program Here.you May Download The Code Here.</p></div><div class="text-center mt-3 text-grey"> 转载请注明原文地址:https://www.9cbs.com/read-110024.html</div><div class="plugin d-flex justify-content-center mt-3"></div><hr><div class="row"><div class="col-lg-12 text-muted mt-2"><i class="icon-tags mr-2"></i><span class="badge border border-secondary mr-2"><h2 class="h6 mb-0 small"><a class="text-secondary" href="tag-2.html">9cbs</a></h2></span></div></div></div></div><div class="card card-postlist border-white shadow"><div class="card-body"><div class="card-title"><div class="d-flex justify-content-between"><div><b>New Post</b>(<span class="posts">0</span>) </div><div></div></div></div><ul class="postlist list-unstyled"> </ul></div></div><div class="d-none threadlist"><input type="checkbox" name="modtid" value="110024" checked /></div></div></div></div></div><footer class="text-muted small bg-dark py-4 mt-3" id="footer"><div class="container"><div class="row"><div class="col">CopyRight © 2020 All Rights Reserved </div><div class="col text-right">Processed: <b>0.073</b>, SQL: <b>9</b></div></div></div></footer><script src="./lang/en-us/lang.js?2.2.0"></script><script src="view/js/jquery.min.js?2.2.0"></script><script src="view/js/popper.min.js?2.2.0"></script><script src="view/js/bootstrap.min.js?2.2.0"></script><script src="view/js/xiuno.js?2.2.0"></script><script src="view/js/bootstrap-plugin.js?2.2.0"></script><script src="view/js/async.min.js?2.2.0"></script><script src="view/js/form.js?2.2.0"></script><script> var debug = DEBUG = 0; var url_rewrite_on = 1; var url_path = './'; var forumarr = {"1":"Tech"}; var fid = 1; var uid = 0; var gid = 0; xn.options.water_image_url = 'view/img/water-small.png'; </script><script src="view/js/wellcms.js?2.2.0"></script><a class="scroll-to-top rounded" href="javascript:void(0);"><i class="icon-angle-up"></i></a><a class="scroll-to-bottom rounded" href="javascript:void(0);" style="display: inline;"><i class="icon-angle-down"></i></a></body></html><script> var forum_url = 'list-1.html'; var safe_token = 'GAV3dNZUFNlbO7ghrNMOuNgekw6USPt4CPdwT8kKXFbgG_2Be4WPdn4HLvbv66WHNKdaJWuTfZMMb0w4I2ihFfuA_3D_3D'; var body = $('body'); body.on('submit', '#form', function() { var jthis = $(this); var jsubmit = jthis.find('#submit'); jthis.reset(); jsubmit.button('loading'); var postdata = jthis.serializeObject(); $.xpost(jthis.attr('action'), postdata, function(code, message) { if(code == 0) { location.reload(); } else { $.alert(message); jsubmit.button('reset'); } }); return false; }); function resize_image() { var jmessagelist = $('div.message'); var first_width = jmessagelist.width(); jmessagelist.each(function() { var jdiv = $(this); var maxwidth = jdiv.attr('isfirst') ? first_width : jdiv.width(); var jmessage_width = Math.min(jdiv.width(), maxwidth); jdiv.find('img, embed, iframe, video').each(function() { var jimg = $(this); var img_width = this.org_width; var img_height = this.org_height; if(!img_width) { var img_width = jimg.attr('width'); var img_height = jimg.attr('height'); this.org_width = img_width; this.org_height = img_height; } if(img_width > jmessage_width) { if(this.tagName == 'IMG') { jimg.width(jmessage_width); jimg.css('height', 'auto'); jimg.css('cursor', 'pointer'); jimg.on('click', function() { }); } else { jimg.width(jmessage_width); var height = (img_height / img_width) * jimg.width(); jimg.height(height); } } }); }); } function resize_table() { $('div.message').each(function() { var jdiv = $(this); jdiv.find('table').addClass('table').wrap('<div class="table-responsive"></div>'); }); } $(function() { resize_image(); resize_table(); $(window).on('resize', resize_image); }); var jmessage = $('#message'); jmessage.on('focus', function() {if(jmessage.t) { clearTimeout(jmessage.t); jmessage.t = null; } jmessage.css('height', '6rem'); }); jmessage.on('blur', function() {jmessage.t = setTimeout(function() { jmessage.css('height', '2.5rem');}, 1000); }); $('#nav li[data-active="fid-1"]').addClass('active'); </script>