Simple learning of. NET paging controls and. net paging controls

Source: Internet
Author: User
Tags tojson

Simple learning of. NET paging controls and. net paging controls

I accidentally saw a post about paging over the past few days and thought it was quite well written. As for these things, I have always known only the principle, but I have never really done it. So I studied the principle of paging and wrote a very simple paging program, I would like to share with you here.

This program uses ado.net to retrieve data. First, it creates a new class PageDAl to retrieve data.

using System;using System.Collections.Generic;using System.Configuration;using System.Data;using System.Data.Common;using System.Data.SqlClient;using System.Linq;using System.Web;namespace page.DAL{  public class PageDal  {    public DataTable GetUserList(out int totalCount, int pageIndex = 1, int pagesize = 10)    {      using (        SqlConnection coon =          new SqlConnection(ConfigurationManager.ConnectionStrings["userConnection"].ConnectionString))      {        coon.Open();        string sqlCount = "select count(F_Id) from Sys_User";        SqlCommand cmd = new SqlCommand(sqlCount, coon);        totalCount = int.Parse(cmd.ExecuteScalar().ToString());        string sql = "select F_Account,F_RealName from (select *,Row_Number() over(order by F_Account) r from Sys_User)as w where r>{0} and r<={1};";        SqlDataAdapter ad = new SqlDataAdapter(String.Format(sql, (pageIndex - 1) * pagesize, (pageIndex * pagesize)), coon);        DataTable dt = new DataTable();        ad.Fill(dt);        return dt;      }    }  }} 

Remember to modify the database connection string in webconfig. You can just create one for the database.

The next step is the general ashx processing program. The html page transfers the request and retrieves data from PageDal.

Using page. DAL; using System. collections. generic; using System. data; using System. linq; using System. text; using System. web; namespace page {// <summary> // summary of WebHandler /// </summary> public class WebHandler: IHttpHandler {public void ProcessRequest (HttpContext context) {try {int pageIndex = int. parse (context. request. form ["pageindex"]); int pageSize = int. parse (context. request. for M ["pagesize"]); PageDal pd = new PageDal (); int totalCount; DataTable dt = pd. getUserList (out totalCount, pageIndex, pageSize); string json = ToJson (dt, "data", totalCount); context. response. contentType = "text/plain"; context. response. write (json);} catch {context. response. write ("error") ;}} public bool IsReusable {get {return false ;}} /// <summary> /// DataTable to convert to Json /// </summary> publi C static string ToJson (DataTable dt, string jsonName, int count) {StringBuilder Json = new StringBuilder (); if (string. isNullOrEmpty (jsonName) jsonName = dt. tableName; Json. append ("{\" "+ jsonName +" \ ": ["); if (dt. rows. count> 0) {for (int I = 0; I <dt. rows. count; I ++) {Json. append ("{"); for (int j = 0; j <dt. columns. count; j ++) {Type type = dt. rows [I] [j]. getType (); Json. append ("\" "+ dt. C Olumns [j]. columnName. toString () + "\": "+ StringFormat (dt. rows [I] [j]. toString (), type); if (j <dt. columns. count-1) {Json. append (",") ;}} Json. append ("}"); if (I <dt. rows. count-1) {Json. append (",") ;}} Json. append ("],"); Json. append ("\" count \ ":" + count + "}"); return Json. toString ();} /// <summary> /// Format String, date, and Boolean // </summary> /// <param name = "str"> </param>/ // <param name = "type "> </Param> // <returns> </returns> private static string StringFormat (string str, Type type) {if (type = typeof (string )) {str = String2Json (str); str = "\" "+ str +" \ "";} else if (type = typeof (DateTime )) {str = "\" "+ str +" \ "";} else if (type = typeof (bool) {str = str. toLower ();} else if (type! = Typeof (string) & string. isNullOrEmpty (str) {str = "\" "+ str +" \ "";} return str ;} /// <summary> /// filter special characters /// </summary> /// <param name = "s"> string </param> /// <returns> json string </returns> private static String String2Json (string s) {StringBuilder sb = new StringBuilder (); for (int I = 0; I <s. length; I ++) {char c = s. toCharArray () [I]; switch (c) {case '\ "': sb. append ("\" "); break; case '\': sb. append ("\\\\"); break; case '/': sb. append ("\/"); break; case '\ B': sb. append ("\ B"); break; case '\ F': sb. append ("\ f"); break; case '\ N': sb. append ("\ n"); break; case '\ R': sb. append ("\ r"); break; case '\ t': sb. append ("\ t"); break; default: sb. append (c); break;} return sb. toString ();}}}

Finally, the html code is displayed.

<! DOCTYPE html> 

After reading the post, I checked the pages made by the company and summarized the pages. I have never seriously thought about paging before, and I think it is quite difficult, however, after a conclusion, we found that as long as you have made it clear by 1.1 points in order, it is not difficult to have a clear idea.

First, take the data in two parts. One is to count the number of all data and the other is to take the data of the current page number. This is very simple. Just write the relevant SQL statement, many SQL statements are written. The statement used to retrieve the current page number is

Select F_Account, F_RealName from (select *, Row_Number () over (order by F_Account) r from Sys_User) as w where r> (pageIndex-1) * pagesize and r <= pageIndex * pagesize
After the data is obtained, the page bar is spelled out and relevant methods are written, such as the home page, the previous page, the next page, and the last page. Then, the total number of data is transmitted, the page number is OK.

<Div id = "pageination" style = "width: 100%"> <a href = "javascript: void (0);" onclick = "GoFirst () "> homepage </a> <a href =" javascript: void (0); "onclick =" GoPre () "> previous page </a> <span> current <input id =" pageindex "type =" text "style =" width: 20px "value =" 1 "disabled =" disabled "/> page, total <input id =" totalcount "type =" text "style =" width: 20px "value =" "disabled =" disabled "/> data, total <input id =" pagecount "type =" text "style =" width: 20px "value = "" Disabled = "disabled"/> page </span> <a href = "javascript: void (0);" onclick = "GoNext () "> next page </a> <a href =" javascript: void (0); "onclick =" GoLast () "> last page </a> </div> function GoFirst () {pageindex = 1; $ (" # pageindex "). val (pageindex); search () ;}; function GoLast () {var pageindex =$ ("# pagecount "). val (); $ ("# pageindex "). val (pageindex); search () ;}; function GoPre () {if (pageindex> 1) {pageindex = pageindex -1; $ ("# pageindex"). val (pageindex); search ();} else {alert ("This is the first page! ") ;}}; Function GoNext () {var pagecount =$ (" # pagecount "). val (); if (pageindex <pagecount) {pageindex = pageindex + 1; $ ("# pageindex "). val (pageindex); search ();} else {alert ("this is the last page! ");}};

The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.

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.