. NET paging control simple learning-practical tips

Source: Internet
Author: User
Tags tojson

The past few days to see a page about the pagination of the post, feel very well written. About these things, they have always been only know the principle, but did not really do, so the study of the principle of pagination himself wrote a very special very simple paging program, here to share with you.

This program takes the data to use the Ado.net, first creates first to take the data the class Pagedal

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[) use Rconnection "]. 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 ()-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; 

 }
    }
  }
}

Then remember to modify the webconfig inside the strings of the connection database, the database to build a random one on the line.

Next is the ASHX general handler, the HTML page that passes the demand, and he takes the data from the Pagedal.

Using page.
DAL;
Using System;
Using System.Collections.Generic;
Using System.Data;
Using System.Linq;
Using System.Text;

Using System.Web; Namespace Page {///<summary>///WebHandler Summary description///</summary> public class Webhandler:ihttphand ler {public void ProcessRequest (HttpContext context) {try {int pageIndex = Int. Parse (context.
        request.form["pageindex"]); int pageSize = Int. Parse (context.
        request.form["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); The catch {context.
      Response.Write ("error");
      } public bool IsReusable {get {false; }///<summary>///DataTable converted to JSON///</summary> public 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.) COLUMNS[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>///formatted character type, date type, Boolean///</summary>///<param name= "str" ></param>// /<param name= "type" ></param>///<returns></returns> private static string StringFormat (s
        Tring 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, it's the HTML code.

<! DOCTYPE html>  

After reading that post, I looked at the paging of the company summed up a bit, had not seriously thought about paging things, I think it is very difficult, but after a summary found that in fact as long as you are in order 1.1 points clear, there is a clear idea, it is not difficult.

First take the data, divided into two parts, one is the number of all the data to the other is to take the current page number of data, this is very simple, I write about the SQL statements on the line, the syntax of the SQL statements are many, I take the current page number with the statement is

Select F_account,f_realname from (select *,row_number ()-F_account R from Sys_user) as W where r> (pageind EX-1) * pagesize and r<=pageindex* pagesize
after the data is taken out is the page to spell well, and the relevant methods to write, such as the first page, the previous one, the next page, last, and so on, and then the total number of data passed over, the calculation of the page is OK.

<div id= "pageination" style= "width:100%" > <a href= "javascript:void (0);" onclick= "Gofirst ()" > Home </a&gt ;  <a href= "javascript:void (0);" onclick= "Gopre ()" > prev </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"/> Strip 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 () > End </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 the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

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.