HomeBackend DevelopmentC#.Net TutorialHow to implement program paging in .NET

How to implement program paging in .NET

Jun 24, 2017 am 09:59 AM
.netPaginationsupportprogram

aspx

查询

 

暂无记录" : ""%>

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

CodeBehind

Namespace

public partial class xxx : Web.UI.ManagePage
{

protected int totalCount;//Total number of records
protected int page;//Current page
protected int pageSize;//Data size per page
protected string keywords = string.Empty;//Query conditions

protected void Page_Load(object sender, EventArgs e)
  {

##   this.keywords = Utils. .GetQueryString("keywords");//Get query conditions            this.pageSize = GetPageSize(10); //Set the data size of each page

               if (!Page.IsPostBack)                                                                                                                                                                                                                                                                            );

##   }

   }

private void RptBind(string _strWhere, string _orderby)                                                                                                                                                                                                       ;                                                                                                                                                                    # This.rptList.DataBind(); lblTotalIncome.Text = Math.Round(totalIncome, 3).ToString(); txtPageNum.Text = this.pageSize.ToString();

string pageU rl=

Utils.CombUrlTxt("xxx.aspx", "keywords={0}&page={1}", this.keywords, "__id__");             PageContent.InnerHtml =
Utils.
OutPageList(this.pageSize, this.page, this.totalCount, pageUrl, 8);
    }




##private int GetPageSize(int _default_size )
                                                                int _pagesize; if (_pagesize > 0)                                                                                                                                                                        }

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));
        }

}

Utils

命名空间

public class Utils
{

public static string GetQueryString(string strName)
        {
            return GetQueryString(strName, false);
        }

public static string GetQueryString(string strName, bool sqlSafeCheck)
        {
            if (HttpContext.Current.Request.QueryString[strName] == null)
                return "";

            if (sqlSafeCheck && !IsSafeSqlString(HttpContext.Current.Request.QueryString[strName]))
                return "unsafe string";

            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 intValue;
        }

public static string CombUrlTxt(string _url, string _keys, params string[] _values)
        {
            StringBuilder urlParams = new StringBuilder();
            try
            {
                string[] keyArr = _keys.Split(new char[] { '&' });
                for (int i = 0; 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)
                    urlParams.Insert(0, "?");
            }
            catch
            {
                return _url;
            }
            return _url + DelLastChar(urlParams.ToString(), "&");
        }

public static string UrlEncode(string str)
        {
            if (string.IsNullOrEmpty(str))
            {
                return "";
            }
            str = str.Replace("'", "");
            return HttpContext.Current.Server.UrlEncode(str);
        }

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

public static string DelLastChar(string str, string strchar)
        {
            if (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             {
                return "";
            }
            int pageCount = totalCount / pageSize;
            if (pageCount             {
                return "";
            }
            if (totalCount % pageSize > 0)
            {
                pageCount += 1;
            }
            if (pageCount             {
                return "";
            }
            StringBuilder pageStr = new StringBuilder();
            string pageId = "__id__";
            string firstBtn = "上一页»";
            string lastBtn = "下一页»";
            string firstStr = "1";
            string lastStr = "" + pageCount.ToString() + "";

            if (pageIndex             {
                firstBtn = "«上一页";
            }
            if (pageIndex >= pageCount)
            {
                lastBtn = "下一页»";
            }
            if (pageIndex == 1)
            {
                firstStr = "1";
            }
            if (pageIndex == pageCount)
            {
                lastStr = "" + pageCount.ToString() + "";
            }
int firstNum = pageIndex - (centSize / 2); //The page number starting in the middle
if (pageIndex firstNum = 2;
int lastNum = pageIndex + centSize - ((centSize / 2) + 1); //The page number at the end of the middle
            if (lastNum >= pageCount) 
               lastNum = pageCount - 1; ;/span>");
pageStr.Append(firstBtn + firstStr);
if (pageIndex >= centSize)
{
pageStr.Append("...< ) {
             pageStr.Append("" + i + "");
                                                                                                                                        pageStr.Append ("" + i + "");
if (PageCount -PageIndex & GT; CentSize- (CentSize / 2))
{
PageStr.appnd ("& LT; span & gt; ... & lt; / span & gt;");
}
               pageStr.Append(lastStr + lastBtn);
                                                                  out out out‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐ } } string newStr)
                                                                                                                                                                                                 , newStr);
}

public static string 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 "";
            }
            return HttpContext.Current.Server.UrlDecode(str);
        }

public static void WriteCookie(string strName, string key, string strValue, int expires)
        {
            HttpCookie cookie = HttpContext.Current.Request.Cookies[strName];
            if (cookie == null)
            {
                cookie = new HttpCookie(strName);
            }
            cookie[key] = UrlEncode(strValue);
            cookie.Expires = DateTime.Now.AddMinutes(expires);
            HttpContext.Current.Response.AppendCookie(cookie);
        }

}

 

Bussiness

命名空间

 public class Business
    {
        private readonly DAL.xxx xxxDal;

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

  }

public List GetList(int pageSize, int pageIndex, string strWhere, string filedOrder, out int recordCount,out decimal totalIncome)
        {
            return xxxDal.GetList(pageSize, pageIndex, strWhere, filedOrder, out recordCount,out totalIncome);
        }

}

 

DAL

命名空间

public partial class xxx
{

public List 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,'无') as uname,
                             ISNULL(b.couserrate,0) as couserrate,
                            ROW_NUMBER() over(order by ocreatetime desc) r from xxx a left join
                            (select cooid,coprate,comoney,corealmoney,codowndrawfee,codrawfee,couupperid,couserrate from xxx where costatus=1)b
                            on a.oid=b.cooid join xxx c on a.opid=c.pid
                            left join xxx d on 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();
                    strSql2.Append(@"select SUM(corealmoney) from xxx a left join
                                    (select cooid,coprate,corealmoney,codowndrawfee,comoney,codrawfee,couupperid,couserrate from xxx where costatus=1)b
                                    on a.oid=b.cooid join xxx c on a.opid=c.pid
                                    left join xxx d on b.couupperid=d.[uid] where a.ostatus=1 ");
                    if (strWhere.Trim() != "")
                    {
strSql2.Append(strWhere);
                                                                                                                                                                                           strSql2. ToString(), filedOrder)).ToList( ;



// ROW_NUMBER high-efficiency paging (only supports MSSQL2005 and above)

public static class PagingHelper {

// Get the paging SQL statement. The default row_number is the key word. This field name is not allowed in all tables.

public static string CreatePagingSql(int _recordCount, int _pageSize, int _pageIndex, string _safeSql, string _orderField)

                                                                                                                                                                                                                                   Count + _pageSize - 1 ) / _pageSize;

//Check the current page number if (_pageIndex        else if (_pageIndex > pageCount)

                                                                                                                                         pageCount) ); newSafeSql.AppendFormat ("SELECT ROW_NUMBER() OVER(ORDER BY {0}) as row_number,", _orderField);
        newSafeSql.Append(_safeSql.Substring(_safeSql.ToUpper().IndexOf("SELECT") + 6));

                                                                                              # ToString ());

sbSql.Append(") AS T"); sbSql.AppendFormat(" WHERE row_number between {0} and {1}", ((_pageIndex - 1) * _pageSize) + 1, _pageIndex * _pageSize);

Return sbSql.ToString();

} // Get the total number of records SQL statement
public static string CreateCountingSql(string _safeSql)
{
return string.Format(" SELECT COUNT(1) AS RecordCount FROM ({0}) AS T ", _safeSql);
    }



}



The above is the detailed content of How to implement program paging in .NET. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
The Continued Relevance of C# .NET: A Look at Current UsageThe Continued Relevance of C# .NET: A Look at Current UsageApr 16, 2025 am 12:07 AM

C#.NET is still important because it provides powerful tools and libraries that support multiple application development. 1) C# combines .NET framework to make development efficient and convenient. 2) C#'s type safety and garbage collection mechanism enhance its advantages. 3) .NET provides a cross-platform running environment and rich APIs, improving development flexibility.

From Web to Desktop: The Versatility of C# .NETFrom Web to Desktop: The Versatility of C# .NETApr 15, 2025 am 12:07 AM

C#.NETisversatileforbothwebanddesktopdevelopment.1)Forweb,useASP.NETfordynamicapplications.2)Fordesktop,employWindowsFormsorWPFforrichinterfaces.3)UseXamarinforcross-platformdevelopment,enablingcodesharingacrossWindows,macOS,Linux,andmobiledevices.

C# .NET and the Future: Adapting to New TechnologiesC# .NET and the Future: Adapting to New TechnologiesApr 14, 2025 am 12:06 AM

C# and .NET adapt to the needs of emerging technologies through continuous updates and optimizations. 1) C# 9.0 and .NET5 introduce record type and performance optimization. 2) .NETCore enhances cloud native and containerized support. 3) ASP.NETCore integrates with modern web technologies. 4) ML.NET supports machine learning and artificial intelligence. 5) Asynchronous programming and best practices improve performance.

Is C# .NET Right for You? Evaluating its ApplicabilityIs C# .NET Right for You? Evaluating its ApplicabilityApr 13, 2025 am 12:03 AM

C#.NETissuitableforenterprise-levelapplicationswithintheMicrosoftecosystemduetoitsstrongtyping,richlibraries,androbustperformance.However,itmaynotbeidealforcross-platformdevelopmentorwhenrawspeediscritical,wherelanguageslikeRustorGomightbepreferable.

C# Code within .NET: Exploring the Programming ProcessC# Code within .NET: Exploring the Programming ProcessApr 12, 2025 am 12:02 AM

The programming process of C# in .NET includes the following steps: 1) writing C# code, 2) compiling into an intermediate language (IL), and 3) executing by the .NET runtime (CLR). The advantages of C# in .NET are its modern syntax, powerful type system and tight integration with the .NET framework, suitable for various development scenarios from desktop applications to web services.

C# .NET: Exploring Core Concepts and Programming FundamentalsC# .NET: Exploring Core Concepts and Programming FundamentalsApr 10, 2025 am 09:32 AM

C# is a modern, object-oriented programming language developed by Microsoft and as part of the .NET framework. 1.C# supports object-oriented programming (OOP), including encapsulation, inheritance and polymorphism. 2. Asynchronous programming in C# is implemented through async and await keywords to improve application responsiveness. 3. Use LINQ to process data collections concisely. 4. Common errors include null reference exceptions and index out-of-range exceptions. Debugging skills include using a debugger and exception handling. 5. Performance optimization includes using StringBuilder and avoiding unnecessary packing and unboxing.

Testing C# .NET Applications: Unit, Integration, and End-to-End TestingTesting C# .NET Applications: Unit, Integration, and End-to-End TestingApr 09, 2025 am 12:04 AM

Testing strategies for C#.NET applications include unit testing, integration testing, and end-to-end testing. 1. Unit testing ensures that the minimum unit of the code works independently, using the MSTest, NUnit or xUnit framework. 2. Integrated tests verify the functions of multiple units combined, commonly used simulated data and external services. 3. End-to-end testing simulates the user's complete operation process, and Selenium is usually used for automated testing.

Advanced C# .NET Tutorial: Ace Your Next Senior Developer InterviewAdvanced C# .NET Tutorial: Ace Your Next Senior Developer InterviewApr 08, 2025 am 12:06 AM

Interview with C# senior developer requires mastering core knowledge such as asynchronous programming, LINQ, and internal working principles of .NET frameworks. 1. Asynchronous programming simplifies operations through async and await to improve application responsiveness. 2.LINQ operates data in SQL style and pay attention to performance. 3. The CLR of the NET framework manages memory, and garbage collection needs to be used with caution.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.