The GridView is a commonly used display data control in ASP.net, and should be very familiar to. NET developers. The GridView comes with many features, including paging, sorting, and so on, But as a. NET developer, it is important to be proficient in using stored procedure paging or third-party custom paging, which is not only a project's need but also a hint of our experience, and I'll talk about using stored procedure paging to implement binding GridView
1. Execute Stored Procedure
There are many examples of SQL paging stored procedures on the Web, but you will find that many of them are not available, for example, some use in or not to paging efficiency is very low, some SP can be paged but the extension is very poor, some efficiency is relatively high, but can not return the total number of query records,
For example, the following page, although relatively simple, but with not in to paging less efficient, and the query table has been fixed dead, cannot be extended, is actually a failure of paging
CREATE PROCEDURE getproductsbypage
@PageNumber int,
@PageSize int
as
declare @sql nvarchar (4000)
Set @sql = ' Select top ' + CONVERT (varchar, @PageSize) + ' * FROM test where ID not in (select top ' + CONVERT (varcha) R, (@PageNumber-1) * @PageSize) + ' ID from test '
exec sp_executesql @sql go
In a word, I think this page is more efficient and very high in overall, and the paging only needs to be performed once SP, paging support multi-table multi-standard query
ALTER PROCEDURE [dbo].
[Proc_sqlpagebyrownumber] (@tbName VARCHAR (255),--The table name @tbGetFields VARCHAR (1000) = ' * ',--returns the field @OrderfldName VARCHAR (255),--The sorted field name @PageS
Ize int=20,--page size @PageIndex int=1,--number @OrderType bit = 0,--0 Ascending, not 0 descending @strWhere VARCHAR (1000) = ',--query criteria
@TotalCount INT OUTPUT--Returns the total number of records) as--=============================================--Author:allen (Liyuxin) --Create date:2012-03-30--Description: Paging Stored procedures (support for multiple table connection queries)--Modify [1]: 2012-03-30--============================ ================= BEGIN DECLARE @strSql VARCHAR (5000)--subject sentence DECLARE @strSqlCount NVARCHAR (500)--query record total subject sentence DECLARE @ Strorder VARCHAR (300)--sort type--------------Total record number---------------IF ISNULL (@strWhere, ') <> ' SET @strSqlCo Unt= ' Select @TotalCout =count (*) from ' + @tbName + ' where 1=1 ' + @strWhere ELSE SET @strSqlCount = ' Select @TotalCout =cou NT (*) from ' + @tbName exec sp_executesql @strSqlCount, N ' @TotalCout int output ', @TotalCounT output--------------paging------------if @PageIndex <= 0 Set @PageIndex = 1 IF (@OrderType <>0) Set @strOr Der= ' ORDER BY ' + @OrderfldName + ' DESC ' ELSE SET @strOrder = ' ORDER BY ' + @OrderfldName + ' ASC ' SET @strSql = ' SELECT * From (SELECT row_number () over (' + @strOrder + ') rowno, ' + @tbGetFields + ' from ' + @tbName + ' WHERE 1=1 ' + @strWhere + ') TB WHERE TB.
Rowno BETWEEN ' +str ((@PageIndex-1) * @PageSize + 1) + ' and ' +str (@PageIndex * @PageSize) EXEC (@strSql) SELECT @TotalCount
End
2. Encapsulating C # Call statements
We are always accustomed to the code to encapsulate, this can improve the reading efficiency of the code, maintenance is more convenient, develop good packaging code habits, we have entered the intermediate from the primary, in fact, this is just a habit
public static class Pagehelper {///<summary>///paging data///</summary>///<param name= "tablename "> Show </param>///<param name=" Returefields "> Return field </param>///<param name=" strwhere "> Condition </param>///<param name= "PageSize" > per page record number </param>///<param name= "curpage" > Current page </param&
Gt <param name= "ROWCOUNT" > Total record number </param>///<param name= "SortField" > Sort field </param>///<retu rns></returns> public static DataTable getpagelist (String tbname, String tbgetfields, string orderfldname, int P agesize, int PageIndex, int ordertype, string strwhere, out int totalcount) {SqlCommand cmd = new SqlCommand ("proc_s
Qlpagebyrownumber ");//stored procedure name Cmd.commandtype = CommandType.StoredProcedure; Cmd. Parameters.addwithvalue ("@tbName", tbname);//table name CMD. Parameters.addwithvalue ("@tbGetFields", tbgetfields), or the field name to display (do not add Select) cmd. Parameters.addwithvalue ("@OrderfldName", ORDERFLDNAME);//Sort index field name cmd. Parameters.addwithvalue ("@PageIndex", PageIndex);//Current First page, page number cmd. Parameters.addwithvalue ("@PageSize", PageSize);//The number of data bars per page cmd. Parameters.addwithvalue ("@OrderType", ordertype);//Set sort type, not 0 value descending cmd. Parameters.addwithvalue ("@strWhere", strwhere), and/or query conditions, do not add where cmd.
Parameters.Add (New SqlParameter ("@TotalCount", SqlDbType.Int)); Cmd. parameters["@TotalCount"].
Direction = ParameterDirection.Output;
DataTable dt = runprocedurecmd (cmd); TotalCount = Convert.ToInt32 (cmd. parameters["@TotalCount"].
Value.tostring ());//Returns the total number of pages returned DT; ///<summary>///Execute stored procedure, return DataTable///</summary>///<param name= "cmd" ></param>/ <returns></returns> public static DataTable Runprocedurecmd (SqlCommand-cmd) {datatable result = new
DataTable (); String connectionString = configurationmanager.appsettings["ConnString"].
ToString ();
SqlConnection conn = new SqlConnection (connectionString);//Your own link string try {if (conn. state = = connectionstate.closed)) {Conn.
Open (); } cmd.
Connection = conn;
SqlDataAdapter da = new SqlDataAdapter (cmd); Da.
Fill (result); Da.
Dispose (); Conn.
Close (); Conn.
Dispose ();
return result; The catch (Exception ex) {conn.
Close (); Conn.
Dispose ();
Throw ex;
}
}
}
3. The GridView uses the third party plug-in to realize pagination
Pagination is now more popular plug-ins are Aspnetpager, this is a more mature plug-ins, online there are many examples.
1), download the Aspnetpager plugin, then right key reference.
2), open the Toolbox, right-click on the tab to select the Import plug-in
3), drag controls to the page, set the properties of the control
Background code
protected void Page_Load (object sender, EventArgs e) {if (!
IsPostBack) {Gridviewbind ("");
} private void Gridviewbind (string sqlwhere) {int totalcount; DataTable dt = BLL. GetList ("Stu_score", "Code,name,begintime,endtime,score", "id", this.) Aspnetpager1.pagesize, this.
Aspnetpager1.currentpageindex, 1,sqlwhere, out totalcount); This.
Aspnetpager1.recordcount = TotalCount; This.
Gridview1.datasource = DT; This.
Gridview1.databind (); This. aspnetpager1.custominfohtml = string. Format ("Current {0}/{1} page total {2} records per page {3}", new object[] {this. Aspnetpager1.currentpageindex, this. Aspnetpager1.pagecount, this. Aspnetpager1.recordcount, this.
Aspnetpager1.pagesize}); //gridview Gaoliang Displays protectedvoid gridview1_rowdatabound1 (object sender, GridViewRowEventArgs e) {if (e.ro W.rowtype = = Datacontrolrowtype.datarow) {e.row.attributes.add ("onmouseover", "c=this.style.backgroundcolor,t
His.style.backgroundcolor= ' #C7DEF3 '); e.row.atTributes.
ADD ("onmouseout", "this.style.backgroundcolor=c");
} }
Foreground code
<table width= "100%" > <tr> <td style= "width:60%"; Float:left; " > Begintime:<asp:textbox id= "txtbegintime" runat= "Server" ></asp:TextBox> Endtime:<asp:textbox id= "Txtendtime" name= "mydate" runat= "Server" ></asp:TextBox> </td> <td style= "width:30%"; Float:right; " > <asp:button id= "btnsearch" runat= "Server" text= "Search" onclick= "btnSearch_Click" class= "Ui-button Ui-widge T ui-state-default ui-corner-all "></asp:Button> <asp:button id=" Btnadd "runat=" "Server" text= "Create" Oncl Ientclick= "Javascript:return false;"/> </td> </tr> <tr> <td colspan= "2" style= "width:100%; Float:left; " > <asp:gridview id= "GridView1" runat= "Server" width= "100%" cellpadding= "2" cssclass= "Gridviewstyle" Cellspaci ng= "2" autogeneratecolumns= "False" > <Columns> <asp:boundfield datafield= "name" headertext= "name"/>
; <asp:boundfield datafield= "Code" HeaderText= "code"/> <asp:boundfield datafield= "begintime" headertext= "BeginTime"/> <asp:boundfield = "Endtime" headertext= "Endtime"/> <asp:boundfield datafield= "score" headertext= "score"/> </columns&
Gt <footerstyle cssclass= "Gridviewfooterstyle"/> <rowstyle cssclass= "Gridviewrowstyle"/> <SelectedRo Wstyle cssclass= "Gridviewselectedrowstyle"/> <pagerstyle cssclass= "Gridviewpagerstyle"/> <Alternatin GrowStyle cssclass= "Gridviewalternatingrowstyle"/>
4, of course, you can change your GridView style, new gridviewsy.css
.
Gridviewstyle {border-right:2px solid #A7A6AA;
border-bottom:2px solid #A7A6AA;
border-left:2px solid white;
border-top:2px solid white;
padding:4px; }
.
Gridviewstyle a {color: #FFFFFF;} .
Gridviewheaderstyle th {border-left:1px solid #EBE9ED;
border-right:1px solid #EBE9ED; }
.
Gridviewheaderstyle {background-color: #5D7B9D;
Font-weight:bold;
Color:white; }
.
Gridviewfooterstyle {background-color: #5D7B9D;
Font-weight:bold;
Color:white; }
.
Gridviewrowstyle {background-color: #F7F6F3;
Color: #333333; }
.
Gridviewalternatingrowstyle {background-color: #FFFFFF;
Color: #284775; }
. Gridviewrowstyle TD,.
Gridviewalternatingrowstyle TD {Border:1px solid #EBE9ED;} .
Gridviewselectedrowstyle {background-color: #E2DED6;
Font-weight:bold;
Color: #333333; }
.
Gridviewpagerstyle {background-color: #284775;
Color: #FFFFFF; }
. Gridviewpagerstyle Table/* To center the paging links*/{margin:0 Auto 0 auto; Pagination controls also add styles, of course the GridView style and pagination styleIn the same CSS. paginator {font:11px Arial, Helvetica, sans-serif;padding:10px 20px 10px 0 margin:0px; paginator a {pad DING:1PX 6px; Border:solid 1px #ddd; Background: #fff;
TEXT-DECORATION:NONE;MARGIN-RIGHT:2PX}. paginator a:visited {padding:1px 6px; border:solid 1px #ddd; Background: #fff;
Text-decoration:none;} . paginator. CPB {padding:1px 6px;font-weight:bold font-size:13px;border:none} paginator a:hover {color: #fff; backg
Round: #ffa501; Border-color: #ffa501; text-decoration:none;}
The most total results display style of the page,
Next we add style to time, add style to time generally select is the DatePicker plug-in, import control using JS and CSS
<script src= "Jquery-ui-1.9.2.custom/js/jquery-1.8.3.js" type= "Text/javascript" ></script>
< Script src= "Jquery-ui-1.9.2.custom/development-bundle/ui/jquery.ui.widget.js" type= "Text/javascript" ></ script>
<script src= "jquery-ui-1.9.2.custom/development-bundle/ui/jquery.ui.core.js" type= "text/" JavaScript "></script>
<script src=" jquery-ui-1.9.2.custom/development-bundle/ui/ Jquery.ui.datepicker.js "type=" Text/javascript "></script><link href=" jquery-ui-1.9.2.custom/ Development-bundle/themes/ui-lightness/jquery.ui.all.css "rel=" stylesheet "type=" Text/css "/>"
The default time plugin is shown in English, we give him a Chinese
New Initdatepicker_cn.js
function Initdatepicker_cn () {$.datepicker.regional[' zh-cn '] = {cleartext: ' Clear ', Clearstatus: ' Purge selected date ', Closetex T: ' Close ', Closestatus: ' Do not change the current selection ', Prevtext: ' < last month ', Prevstatus: ' Show last month ', Prevbigtext: ' << ', Prevbigstatus: ' Show last year ', Nexttext: ' Next month > ', Nextstatus: ' Show next month ', Nextbigtext: ' >> ', Nextbigstatus: ' Show next year ', Currenttext:
' Today ', Currentstatus: ' Show this month ', monthnames: [' January ', ' February ', ' March ', ' April ', ' May ', ' June ', ' July ', ' August ', ' September ', ' October ', ' November ', ' December '], Monthnamesshort: [' A ', ' two ', ' three ', ' four ', ' five ', ' six ', ' seven ', ' eight ', ' nine ', ' ten ', ' 11 ', ' 12 ', Monthstatus: ' Select Month ', Yearstatus: ' Choose Year ', Weekheader: ' Weeks ', Weekstatus: ' Week of the Year ', DayNames: [' Sunday ', ' Monday ', ' Tuesday ', ' Wednesday ', ' Thursday ', ' Friday ', ' Saturday '], Daynamessho RT: [' Sunday ', ' Monday ', ' Tuesday ', ' Wednesday ', ' Thursday ', ' Friday ', ' Saturday '], daynamesmin: [' Day ', ' one ', ' two ', ' three ', ' four ', ' five ', ' six '], Daystatus: ' Set DD as a
Week start ', Datestatus: ' Select M-month D-Day, DD ', DateFormat: ' Yy-mm-dd ', firstday:1, initstatus: ' Please select Date ', Isrtl:false}; $.datepicker.setdefaults ($.datepicker.regional[' ZH-CN ']); }
Front page Add jquery script, of course maincontent_txtbegintime is your time tag ID, sometimes you may not show it, do not hurry right click on the source file will find that the ID of the control and the ID of the HTML tag is not the same, we must choose the ID of the tag
<script type= "Text/javascript" >
jQuery (function () {
initdatepicker_cn ();
$ (' #MainContent_txtBeginTime '). DatePicker ({changemonth:true, changeyear:true});
</script>
Effect Chart:
If you follow these four steps to do so, a simple and practical pagination display page will be displayed in front of you, welcome to discuss.