1. Introduction
ASP. NET 2.0 provides us with a brand new gridview control, which adds many new features based on the DataGrid, such as not writing a rowCodeIt can be combined with the data source control to achieve data display and paging, but this paging efficiency is low, which is to read all the data from the database at a time before paging, if there is a small amount of data, you can achieve rapid development, but if the database stores a large amount of data, this operation performance is relatively low, so we generally write our own data reading method, when binding a new page in the pageindexchanging event, a problem occurs. If the gridview cannot correctly calculate the total number of pages when only one page is read, the page button cannot be displayed correctly, therefore, you need to consider scaling it. In addition, the datalist control provides flexible template settings to display record content, but its biggest weakness is that it does not support paging. We also try to expand datalist to add the paging feature.
2. Analysis
The reason why you need to put the gridview and datalist together is that no matter which data binding control needs to perform similar operations to generate a list of paging links. The gridview control supports pagination. Therefore, when developing a custom table control, you only need to add the corresponding button Server Control, set the commandname attribute to page, and set the commandargument attribute to a specific value, the page change event can be captured by the gridview. To avoid the occurrence of "Magic characters" in the Code, the constant class is defined to save the string constants used. However, this method is not applicable to datalist because datalist cannot receive client-side sending events. This is also a difference between the datalist class and the gridview class-the datalist class does not implement the ipostbackeventhandler interface. To enable datalist to receive client-side sending back and trigger paging events, you need to enable custom datalist to implement the ipostbackeventhandler interface, and use the Custom Event parameter class to transmit page number information when an event is triggered.
Now the custom gridview and datalist controls can implement pagination. To make the two have a uniform paging appearance, the paging base class is defined to implement the paging function and for datalist paging, inherit the paging base class and set the paging button's sending-back script. Finally, in order to add the pagination button as a whole to the table, so that it inherits from tablecell (cells in the table ).
3. Implementation
3.1 create a constant class constant that saves the command string
Public class constant {public const string first_page = "first"; Public const string prev_page = "Prev"; Public const string next_page = "Next"; Public const string last_page = "last "; public const string page_argument = "page"; Public const char argument_splitter = '$ ';}
The commandargument attribute in the pagination button is set as follows:
| Attribute |
Description |
|
First |
Move to the first page |
| Last |
Move to the last page |
| Prev |
Move to previous page |
| Next |
Move to next page |
| A number |
Move to a specific page |
3.2 define the datapager class to generate paging links. This class inherits from the tablecell class and defines private variables to calculate page numbers (pagersettings class is.. Net pre-defined class, stores information about paging settings)
Public class datapager: tablecell {private int _ pageindex; private int _ recordcount; private int _ pagesize; private int _ pagecount; private pagersettings _ settings ;}
3.3 define the constructor, receive the current page index, total number of records, page size information, and calculate the total page number based on the data, and then call the generatepage method to generate a page
Public datapager (pagersettings setting, int pageindex, int recordcount, int pagesize) {_ settings = setting; _ pageindex = pageindex; _ recordcount = recordcount; _ pagesize = pagesize; _ pagecount = _ recordcount % _ pagesize = 0? _ Recordcount/_ pagesize: _ recordcount/_ pagesize + 1; generatepage ();}
3.3 compile the generatepage method and generate a paging link with or without a number based on pagersetting settings:
Private void generatepage () {If (_ settings. mode = pagerbuttons. nextprevious | _ settings. mode = pagerbuttons. nextpreviusfirstlast) {generateprevnextpage ();} else if (_ settings. mode = pagerbuttons. numeric | _ settings. mode = pagerbuttons. numericfirstlast) {generatenumericpage ();}}
3.4 compile a method to generate two types of paging links:
Private void generateprevnextpage () {generatepage (false);} private void generatenumericpage () {generatepage (true );}
3.5 The generatepage method is called when a page is generated. This method creates a series of linkbuttons and sets the commandargument and commandname attributes. The implementation of this method is as follows:
Private void generatepage (bool generatenumber) {This. controls. add (New literalcontrol ("& nbsp;"); If (_ recordcount> 0) {This. controls. add (New literalcontrol ("?? & Nbsp; "); this. controls. add (New literalcontrol (_ recordcount. tostring (); this. controls. add (New literalcontrol ("& nbsp ;?????? & Nbsp ;???? & Nbsp; "); this. controls. add (New literalcontrol (_ pagesize. tostring (); this. controls. add (New literalcontrol ("& nbsp ;?????? & Nbsp; ");} This. controls. add (New literalcontrol (_ pageindex + 1 ). tostring (); this. controls. add (New literalcontrol ("/"); this. controls. add (New literalcontrol (_ pagecount. tostring (); this. controls. add (New literalcontrol ("& nbsp;"); linkbutton btnfrist = new linkbutton (); linkbutton btnprev = new linkbutton (); linkbutton btnnext = new linkbutton (); linkbutton btnlast = ne W linkbutton (); If (! String. isnullorempty (_ settings. firstpageimageurl) {btnfrist. TEXT = " _ settings. pagebuttoncount) {if (I <_ pageindex-leftcount & _ pagecount-1-I> _ settings. pagebuttoncount-1) {continue;} else if (I> _ pageindex + rightcount & I> _ settings. pagebuttoncount-1) {continue;} if (I = _ pageindex) {This. controls. add (New literalcontrol ("<span style = 'color: red; font-weight: bold '>" + (I + 1 ). tostring () + "</span>");} else {linkbutton lB = new linkbutton (); lb. TEXT = (I + 1 ). tostring (); lb. commandname = constant. page_argument; lb. commandargument = (I + 1 ). tostring (); this. controls. add (LB);} This. controls. add (New literalcontrol ("& nbsp;") ;}} if (this. _ pageindex> = _ pagecount-1) {btnnext. enabled = btnlast. enabled = false;} else {btnnext. enabled = btnlast. enabled = true;} This. controls. add (btnnext); this. controls. add (New literalcontrol ("& nbsp;"); this. controls. add (btnlast); this. controls. add (New literalcontrol ("& nbsp ;"));}
3.6 create a custom gridview class that inherits from the default gridview (system. Web. UI. webcontrols. gridview) in ASP. NET ):
[Toolboxdata (@ "<{0}: gridview runat = 'server'> </{0}: gridview>")] public class gridview: system. web. UI. webcontrols. gridview {}
3.7 define the gridview attribute, add the total number of records stored in recordcound, and overwrite the pageindex and pagecount attributes to store the current page index and the total number of pages, in addition, the mouseoverbackgroundcolor attribute is defined to change the background color when the mouse moves over the data row.
Public int recordcount {get {object o = viewstate ["recordcount"]; return O = NULL? 0: convert. toint32 (o) ;}set {viewstate ["recordcount"] = value ;}} public override int pageindex {get {object o = viewstate ["pageindex"]; return o = NULL? 0: Convert. toint32 (o);} set {viewstate ["pageindex"] = value ;}} public override int pagecount {get {int pagecount = recordcount % pagesize = 0? Recordcount/pagesize: recordcount/pagesize + 1; return pagecount;} public color mouseoverbackgroundcolor {get {object o = viewstate ["mouseoverbackgroundcolor"]; return O = NULL? Color. Silver: (color) O ;}set {viewstate ["mouseoverbackgroundcolor"] = value ;}}
3.8 override the onrowcreated method. When creating a data row, first add the background color JavaScript, and then create a page number link cell based on the page information to add it to the table.
Protected override void onrowcreated (gridviewroweventargs e) {If (E. row. rowtype = datacontrolrowtype. datarow) {e. row. attributes. add ("onmouseover", "bgcolor = This. style. backgroundcolor; this. style. backgroundcolor = '"+ colortranslator. tohtml (mouseoverbackgroundcolor) + "';"); E. row. attributes. add ("onmouseout", "this. style. backgroundcolor = bgcolor; ");} If (E. row. rowtype = datacontrolrowtype. PAGER) {e. row. controls. clear (); tablecell Tc = new datapager (pagersettings, pageindex, recordcount, pagesize); TC. columnspan = This. columns. count; E. row. controls. add (TC);} base. onrowcreated (E );}
3.9 In order to scroll to the previous page When deleting the last row of data, the onrowdeleted method is rewritten:
Protected override void onrowdeleting (gridviewdeleteeventargs e) {If (this. Rows. Count = 1) This. pageindex = This. pageindex-1> = 0? This. pageindex-1: 0; base. onrowdeleting (E );}
3.10 declare and define a custom gridview on the website:
<CC: gridview id = "gdvdata" runat = "server" pagesize = "4" allowpaging = "true" onpageindexchanging = "gdvdata_pageindexchanging" recordcount = "0" datakeynames = "ID" font-size = "12px" onrowdeleting = "gdvdata_rowdeleting" width = "500px" autogeneratecolumns = "false" backcolor = "white" bordercolor = "# ffe0c0" borderstyle = "NONE" borderwidth = "1px" cellpadding = "4" mouseoverbackgroundcolor = "255,224,192" onrowdeleted = "gdv Data_rowdeleted "> <columns> <asp: boundfield datafield =" ID "headertext = "???? "/> <Asp: boundfield datafield =" name "headertext = "???? "/> <Asp: boundfield datafield =" favor "headertext = "???? "/> <Asp: commandfield showdeletebutton =" true "headertext = "???? "/> </Columns> <pagersettings pagebuttoncount =" 5 "/> <rowstyle backcolor =" white "forecolor =" #330099 "/> <footerstyle backcolor =" # ffffcc "forecolor = "#330099"/> <pagerstyle backcolor = "# ffffcc" forecolor = "#330099" horizontalalign = "center"/> <selectedrowstyle backcolor = "# ffcc66" font-bold = "True" forecolor = "#663399"/>
3.11 write post code to bind to the Data source:
Protected void page_load (Object sender, eventargs e) {If (! Ispostback) This. binddata ();} private void binddata () {userquery query = NULL; object o = viewstate ["query"]; If (O = NULL) query = new userquery (); else query = (userquery) O; int Total = 0; ilist <user> Users = users. getusers (query, gdvdata. pageindex, gdvdata. pagesize, out total); gdvdata. recordcount = total; gdvdata. datasource = users; gdvdata. databind ();}
3.12 compile pageindexchanging and rowdeleting event processingProgram:
Protected void gdvdata_pageindexchanging (Object sender, gridviewpageeventargs e) {gdvdata. pageindex = E. newpageindex; this. binddata ();} protected void gdvdata_rowdeleting (Object sender, gridviewdeleteeventargs e) {int id = convert. toint32 (gdvdata. datakeys [E. rowindex]. value); users. deleteuser (ID); this. binddata ();}
3.13 preview the page in the browser (the users and user classes in this Code are not provided, and you can write them by yourself. The users class is equivalent to a logic class that allows you to query and delete users, user class ).
4. Summary
In this task, you have created a gridview control that can automatically implement paging. the pagination link generation operation is extracted separately and the datapager class is created, use linkbutton in this class and set commandname and commandargument to implement page feed. Next task we will add the paging feature for datalist based on this class.
ASP. NET Custom ControlsArticle
Preface
Simple star control on the first day
Star controls with custom styles the next day
On the third day, use the star widget in the control status.
Fold panel custom controls on the fourth day
Star controls that can be scored on the fifth day
Star controls that can be bound to data sources on the sixth day
Develop list controls with rich features on the seventh day
Metric days: displays the data binding controls for multiple entry star rating
The ninth day custom gridview
Datalist that implements the paging function on the tenth day
Download all source code
Download this series of articles in PDF