Exécution Exécution

Maison  >  Article  >  développement back-end  >  Comment implémenter la pagination du programme dans .NET

Comment implémenter la pagination du programme dans .NET

零下一度
零下一度original
2017-06-24 09:59:481924parcourir

aspx

查询

 

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

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

CodeBehind

espace de noms

classe partielle publique xxx : Web.UI.ManagePage
{

protected int totalCount;//Nombre total d'enregistrements
page int protégée;//Page actuelle
protected int pageSize;//Taille des données par page
protected string keywords = string.Empty;//Conditions de requête

protected void Page_Load(object sender, EventArgs e)
  {

  this.keywords = Utils. .GetQueryString("keywords");//Obtenir les conditions de requête
this.pageSize = GetPageSize(10); //Définir la taille des données de chaque page

If (!Page.IsPostBack)
{

🎜>private void RptBind(string _strWhere, chaîne _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 = Utils. OutPageList (this.pageSize, this.page, this.totalCount, pageUrl, 8)                                  );               int _pagesize;                 { if (_pagesize > 0)

                                                                          re tourner _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)
        {
             _pagesize;
            si (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)) ;
        }

}

Utils

命名空间

utils de classe publique
{

chaîne statique publique GetQueryString(string strName)
        {
            return GetQueryString(strName, false);
        }

chaîne statique publique GetQueryString(string strName, bool sqlSafeCheck)
        {
            if (HttpContext.Current.Request.QueryString[strName] == null)

            return HttpContext.Current .Request.QueryString[strName];
        }



public static bool IsSafeSqlString(string str)
        {

             return !Regex.IsMatch(str, @"[ -|;|,|/|(|)|[|]|}|{|%|@|*|!|']");

        }


public 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 valeurint;
        }

chaîne statique publique CombUrlTxt(string _url, string _keys, params string[] _values)
        {
            StringBuilder urlParams = new StringBuilder();
            essayer
           {
                chaîne [] keyArr = _keys.Split(new char[] { '&' });
                for (int i = 0; i < keyArr.Length; i++)
                {
                    if (!string. IsNullOrEmpty(_values[i]) && _values[i] != "0")
                    {
                       _values[i] = UrlEncode(_values[i]);
                        urlParams.Append(string.Format(keyArr [i], _values) + "&");
                    }
               }
              if (!string.IsNullOrEmpty(urlParams.ToString()) && _url.IndexOf("?") = = -1) <# 🎜>            }
            return _url + DelLastChar(urlParams.ToString(), "&");
        }



chaîne statique publique UrlEncode(string str)
        {
           if (string.IsNullOrEmpty(str))
            {

               return "";

            }            str = str.Replace("'", "");
                     return  }



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


chaîne statique publique DelLastChar(string str, string strchar)

        {

            si (string.IsNullOrEmpty(str))                return "";            if (str.LastIndexOf(strchar) >= 0 && str.LastIndexOf(strchar) == str.Length - 1)

            {

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



//返回分页页码

chaîne statique publique 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 "";
            }
            StringBuilder pageStr = new StringBuilder();
            string pageId = "__id__";
            string firstBtn = "上一页»";
            string lastBtn = "下一页»";
            string firstStr = "1";
            string lastStr = "" + pageCount.ToString() + "";

            if (pageIndex <= 1)
            {
                firstBtn = "«上一页";
            }
            if (pageIndex >= pageCount)
            {
               lastBtn = "下一页»< ;/span>";
            }
            if (pageIndex == 1)
            {
                firstStr = "1" ;
}
            if (pageIndex == pageCount)
            {
               lastStr = "" + pageCount.ToString() + "";
            }
int FIRSTNUM = PageIndex- (CentSize /2); // Le numéro de page commence au milieu
if (pageindex & lt; CentSize)
firstNum = 2; int LastNum = Pageindex + CentSize- (Cen (CEN CEN tsize / 2) + 1); // Le numéro de page se termine au milieu
if (LastNum & GT; = PageCount)
LastNum = PageCount -1; 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("" + i + "") ;
                                                      pageCount - pageIndex > centSize - ((centSize / 2)))
                                                                                         pageStr .Append(lastStr + lastBtn);
                                                                                       return pageStr.ToString(); >                                                                                                                                                                                                  retourner originalStr.Replace (oldStr, newStr );
}

chaîne statique publique 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 "";
        }

chaîne statique publique UrlDecode(string str)
        {
            if (string.IsNullOrEmpty(str))
             {
return "";
            }
            return HttpContext.Current.Server.UrlDecode(str);
        }

public static void WriteCookie(string strName, string key, string strValue, int expire)
        {
                        cookie = nouveau HttpCookie(strName );
            }
            cookie[key] = UrlEncode(strValue);
            cookie.Expires = DateTime.Now.AddMinutes(expires);
            HttpContext.Current.Response.Append Cookie(cookie);


 public class Business
    {

       privé en lecture seule DAL.xxx xxxDal;

public Business()

        {

            xxxDal = new DAL.xxx();

  }

liste publique GetList(int pageSize, int pageIndex, string strWhere, string fieldOrder, out int recordCount,out décimal totalIncome)

        {            return xxxDal.GetList(pageSize, pageIndex, strWhere, fieldOrder, out recordCount,out totalIncome);
        antecement 🎜>

cours partiel public xxx

{

Liste publique GetList(int pageSize, int pageIndex, string strWhere, string fieldOrder, out int recordCount,out décimal totalIncome)
        {
            totalIncome = 0;
            StringBuilder strSql = new StringBuilder();
            strSql.Append (@"select a.oid,ocreatetime,a.oaccname,a.oacctel,(select ucardnum from AppUser où uid=a.ouid) as ucardnum,c.pname,
                           otype,ISNULL(b.corealmoney,0) comme corealmoney,ISNULL(b.cooid,0) comme cooid,
                            omoney,ISNULL(coprate,0) coprate,ISNULL(codrawfee,0) codrawfee,ISNULL(codowndrawfee,0) codowndrawfee,ISNULL(d.uname,'无') comme uname,
                             ISNULL(b.couserrate,0) comme couserrate,
                           ROW_NUMBER() over(order bycreate otime desc) r from xxx a left join
                            (sélectionnez cooid, coprate, comoney, corealmoney,codowndrawfee,codrawfee,couupperid,couserrate de xxx où costatus=1)b
                           sur a.oid=b.cooid rejoindre xxx c sur a.opid=c.pid
                           gauche rejoindre xxx d sur b.coupperid =d.[uid] où 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();
                    strSql2.Append (@"select SUM(corealmoney) from xxx a left join
                                    (sélectionnez cooid, coprate, corealmoney, codowndrawfee, comoney ,codrawfee,couupperid,couserrate à partir de xxx où costatus=1)b
                                  sur a.oid=b.cooid rejoindre xxx c sur a.opid=c.pid
                                    gauche join xxx d sur b.couupperid=d. [uid] où a.ostatus=1 ");
                     if (strWhere.Trim() != "")
                     {
strSql2.Append (strWhere); pageIndex, strSql.ToString(), fileOrder)).ToList( ;



// ROW_NUMBER pagination haute efficacité (prend uniquement en charge MSSQL2005 et supérieur)

classe statique publique PagingHelper {

// Obtenez l'instruction SQL de pagination, le numéro de ligne par défaut est le mot clé, ce nom de champ est non autorisé dans toutes les tables

chaîne statique publique CreatePagingSql(int _recordCount, int _pageSize, int _pageIndex, string _safeSql, _orderField)                                                                                                   int pageCount = (_recordCount + _pageSize - 1 ) /_pageSize;

// Vérifiez le nombre de pages actuelles if (_pageindex & lt; 1) {

_pageindex = 1

🎜> else if (_pageindex & gt; ; nombre de pages)                                      _pageIndex =                                                                      plus ancien 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));

> // L'épissage dans l'instruction SQL finale

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

}

          { chaîne de retour. Format (" SELECT COUNT (1) AS RecordCount FROM ({0}) AS T ", _safeSql); 🎜>

Ce qui précède est le contenu détaillé de. pour plus d'informations, suivez d'autres articles connexes sur le site Web de PHP en chinois!

Déclaration:
Le contenu de cet article est volontairement contribué par les internautes et les droits d'auteur appartiennent à l'auteur original. Ce site n'assume aucune responsabilité légale correspondante. Si vous trouvez un contenu suspecté de plagiat ou de contrefaçon, veuillez contacter admin@php.cn