Heim >Backend-Entwicklung >C#.Net-Tutorial >So implementieren Sie Programm-Paging in .NET

So implementieren Sie Programm-Paging in .NET

零下一度
零下一度Original
2017-06-24 09:59:482005Durchsuche

aspx

查询

 

<%#rptList.Items.Count == 0 ? "暂无记录" : ""%>

显示 OnTextChanged="txtPageNum_TextChanged" AutoPostBack="True">条/页

CodeBehind

Namespace

öffentliche Teilklasse xxx : Web.UI.ManagePage
{

protected int totalCount;//Gesamtzahl der Datensätze
protected int page;//Aktuelle Seite
protected int pageSize;//Datengröße pro Seite
protected string keywords = string.Empty;//Abfragebedingungen

protected void Page_Load(object sender, EventArgs e)
  {

  this.keywords = Utils. .GetQueryString("keywords");//Abfragebedingungen abrufen
this.pageSize = GetPageSize(10); //Datengröße jeder Seite festlegen

If (!Page.IsPostBack)
{

RptBind("Abfrageanweisung nach Schlüsselwörtern integriert", "Feld aufsteigend sortieren/ desc" ; 🎜>private void RptBind(string _strWhere, string. _orderby)

                                                                                                     s ;

                       BLL.Business bll = new BLL.Business(); > This.rptList.DataBind(); lblTotalIncome.Text = Math.Round(totalIncome, 3).ToString(); txtPageNum.Text = this.pageSize.ToString();        string pageUrl = Utils.

CombUrlTxt ("xxx.aspx", "keywords={0}&page={1}", this.keywords, "__id__");

              PageContent.InnerHtml = OutPageList(this.pageSize, this.page, this.totalCount, pageUrl, 8);   }

private int GetPageSize(int _default_size. )
                                     int _pagesize;               {
if (_pagesize > 0)
                                                            return _default_size;
>

protected void lbtnSearch_Click(object sender, EventArgs e)
        {
            Response.Redirect(Utils.CombUrlTxt("xxx.aspx", "keywords={0}" , txtKeywords.Text));
       }

protected void txtPageNum_TextChanged(object sender, EventArgs e)
        {
            int. _pagesize;
           if (int. TryParse(txtPageNum.Text.Trim(), out _pagesize))
            {
                if (_pagesize > 0)
              
Utils.WriteCookie("detail_page_size", " NovelPage", _pagesize.ToString(), 14400);                }
            }
            Response.Redirect(Utils.CombUrlTxt("xxx.aspx", "keywords={0}", this.keywords)) ; >

Public Class Utils
{

public static string GetQueryString(string strName)

        {

            return GetQueryString(strName, false);        }

öffentliche statische Zeichenfolge GetQueryString(string strName, bool sqlSafeCheck)        {

            if (HttpContext.Current.Request.QueryString[strName] == null)

return "";
if ( .Request.QueryString[strName];
        }


public static bool IsSafeSqlString(string str)
        {
            return !Regex.IsMatch(str, @"[ -|; |, |/| (|) | [|] |} | {|%|@|*|! | '] "); static int GetQueryInt(string strName, int defValue)
        {

            return StrToInt(HttpContext.Current.Request.QueryString[strName], defValue);

        }

public static int StrToInt(string expression, int defValue)
        {
            if (string.IsNullOrEmpty(expression) || expression.Trim().Length >= 11 || !Regex. IsMatch(expression.Trim(), @"^([-]|[0-9])[0-9]*(.w*)?$"))
                return defValue;

int rv;
            if (Int32.TryParse(expression, out rv))
                return rv;

            return Convert.ToInt32(StrToFloat(expression, defValue));
        }

public static float StrToFloat(string expression, float defValue)
        {
            if ((expression == null) || (expression.Length > 10))
                return defValue;

            float intValue = defValue;
            if (expression != null)
            {
               bool IsFloat =. Regex.IsMatch(expression , @"^([-]|[0- 9])[0-9]*(.w*)?$");
               if (IsFloat)
                   float.TryParse(expression, out intValue);
           . }
            return intValue;
        }

öffentliche statische Zeichenfolge CombUrlTxt(string _url, string _keys, params string[] _values)
        {
            StringBuilder urlParams = new StringBuilder();
           . versuchen Sie es
            {
                Zeichenfolge [] keyArr = _keys.Split(new char[] { '&' });
                for (int i = 0; i < keyArr.Length; i++)
                {
                    if (!string. IsNullOrEmpty(_values[i]) && _values[i] != "0")
                               urlParams.Append(string.Format(keyArr [i], _values) + "&");
                                       urlParams.Insert(0, "?");
                       }
            return _url + DelLastChar(urlParams.ToString(), "&");
        }



public static string UrlEncode(string str)
        {
            if (string.IsNullOrEmpty(str))
            {
               return "";

           

//删除最后结尾的指定字符后的字符



public static string DelLastChar(string str, string strchar)
       . {
            wenn (string.IsNullOrEmpty(str))
                return "";

            if (str.LastIndexOf(strchar) >= 0 && str.LastIndexOf(strchar) == str.Length - 1)

            {                return str.Substring(0, str.LastIndexOf(strchar));            }

            return str;

        分页页码

public static string OutPageList(int pageSize, int pageIndex, int totalCount, string linkUrl, int centSize)
        {
            //计算页数
            if (totalCount < 1 || pageSize < 1)
            {
               return "";
            }
            int pageCount = totalCount / pageSize;
            if (pageCount < 1)
            {
                return "";
            }
            if (totalCount % pageSize > 0)
                  pageCount += 1;
           .          if (pageCount <= 1)
            {
Return ""; (pageIndex-1).ToString()) + "">上一页»";
            string lastBtn = "下一页»";
            string firstStr = "1";
            string lastStr = "" + pageCount.ToString() + "";

            if (pageIndex <= 1)
            {
                firstBtn = "« ";" gt;下一页»<
}
            if (pageIndex == pageCount)
            {
                lastStr = "" + pageCount.ToString() + "";
            }
int FIRSTNUM = PAGEINDEX- (CentSize /2); // Die Seitenzahl beginnt in der Mitte
if (pageindex & lt; CentSize)
firstnum = 2;
int LastNum = Pageindex + CentSize- (CEN tsize / 2) + 1); // Die Seitenzahl endet in der Mitte
if (LastNum & GT; = PageCount)
LastNum = PageCount -1;
PageStr.append ("& LT; span & gt; common" + TotalCount + "records & lt ;/span>");
pageStr.Append(firstBtn + firstStr);
if (pageIndex >= centSize)
pageStr.Append(" < span>...< ;/span>n");
                                                                                                                                                           pageStr.Append("" + i + "") ; {
                                        pageStr.Append("< ;a href="" + ReplacementStr(linkUrl, pageId, i.ToString()) + "">" + i + "");
PageCount - PageIndex & gt; 🎜> }

öffentliche statische Zeichenfolge GetCookie(string strName, string key)
        {
            if (HttpContext.Current.Request.Cookies != null && HttpContext.Current.Request.Cookies[strName] != null && HttpContext.Current.Request.Cookies[strName][key] != null)
                return UrlDecode(HttpContext.Current.Request.Cookies[strName][key].ToString());

            return "";
        }

public static string UrlDecode(string str)
        {
            if (string.IsNullOrEmpty(str))
            {
return "";
            string strValue, int läuft ab)
        {
                          cookie = new HttpCookie(strName );
           endCookie(cookie);

   & 🎜>


 public class Business
    {
        private readonly DAL.xxx xxxDal;



public Business()
        {
            xxxDal = new DAL.xxx();

  }

public List GetList(int pageSize, int pageIndex, string strWhere, string fileOrder, out int recordCount,out decimal totalIncome)

        {

            return xxxDal.GetList(pageSize, pageIndex, strWhere, fileOrder, out recordCount,out totalIncome);   & 🎜>

öffentliche Teilklasse xxx{

öffentliche Liste GetList(int pageSize, int pageIndex, string strWhere, string filedOrder, out int recordCount,out decimal totalIncome)
        {
            totalIncome = 0;
            StringBuilder strSql = new. StringBuilder();
            strSql.Append (@"select a.oid,ocreatetime,a.oaccname,a.oacctel,(select ucardnum from AppUser where uid=a.ouid) as ucardnum,c.pname,
                           otype,ISNULL(b.corealmoney,0) as corealmoney,ISNULL(b.cooid,0) as cooid,
                            omoney,ISNULL(coprate,0) coprate,ISNULL(codrawfee,0) codrawfee,ISNULL(codowndrawfee,0) codowndrawfee,ISNULL(d.uname,'无') als uname,
                             ISNULL(b.couserrate,0) als couserrate,
                           ROW_NUMBER() over(order by ocreatetime desc) r from xxx a left join
                            (wählen Sie cooid, coprate, comoney, corealmoney,codowndrawfee,codrawfee,couupperid,couserrate from xxx where costatus=1)b
                          xxx d auf b.couupperid =d.[uid] where a.ostatus=1 ");
            if (strWhere.Trim() != "")
            {
                strSql.Append(strWhere);
            }
            using (var context = DataBaseConnection.GetSdkBaseConnection())
            {
              recordCount =. context.ExecuteScalar(PagingHelper.CreateCountingSql(strSql.ToString()));
                if (recordCount > 0)
                {
                    StringBuilder strSql2 = new StringBuilder();                                  (wählen Sie cooid,coprate,corealmoney,codowndrawfee,comoney ,codrawfee,couupperid,couserrate from xxx where costatus=1)b
                                  on a.oid=b.cooid join xxx c on.                              links beitreten xxx d auf b.couupperid=d. [uid] where a.ostatus=1 ");
                    if (strWhere.Trim() != "")
                    {
strSql2.Append (strWhere); pageIndex, strSql.ToString(), filedOrder)).ToList( ;



// ROW_NUMBER hocheffizientes Paging (unterstützt nur MSSQL2005 und höher)

öffentliche statische Klasse PagingHelper {

// Holen Sie sich die Paging-SQL-Anweisung, die Standardzeilennummer ist das Schlüsselwort, dieser Feldname ist nicht in allen Tabellen zulässig

public static string CreatePagingSql(int _recordCount, int _pageSize, int _pageIndex, string _safeSql, string. _orderField)                                                                                                int pageCount = (_recordCount + _pageSize - 1 ) /_pageSize;

// Überprüfen Sie die Anzahl der aktuellen Seiten if (_pageindex & lt; 1) {

_pageindex = 1;

🎜> else if (_pageindex & gt ; pageCount)                                     _pageIndex =                                                        ilder newSafeSql = new StringBuilder();
newSafeSql.AppendFormat ("SELECT ROW_NUMBER() OVER(ORDER BY {0}) as row_number,", _orderField);
        newSafeSql.Append (_safeSql.Substring(_safeSql.ToUpper().IndexOf("SELECT") + 6));

> // Das Zusammenfügen in die endgültige SQL-Anweisung

StringBuilder SBSQL = New StringBuilder (); > SBSQL.APPEND ("Select * From ("); ray ()); _pageIndex * _pageSize); return sbSql.ToString();

}

          { return string. Format(" SELECT COUNT(1) AS RecordCount FROM ({0}) AS T ", _safeSql);
    }



}



Das obige ist der detaillierte Inhalt vonSo implementieren Sie Programm-Paging in .NET. Für weitere Informationen folgen Sie bitte anderen verwandten Artikeln auf der PHP chinesischen Website!

Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn