search
HomeBackend DevelopmentC#.Net TutorialASP.NET high-performance paging code

I have been struggling with paging recently. I remember that I posted a method to modify DW ASP paging before, and later wrote a manual ASP paging. Now that I enter .NET, of course I have to cooperate with stored procedures to create pure manual high-performance paging.

Why is it called high performance? Why do we need to build it manually instead of using the existing paging controls of .NET? This goes back to when I modified DW ASP paging, and I didn’t know much about programming at that time. I only know how to fix things, let alone talk about performance issues. I was very upset at the time, so I asked my personal technical director, Mr. Zhang, to help me take a look. At that time, Mr. Zhang looked at me with a disdainful look. , and said: Is it worth it?

Then I hand-created ASP paging and couldn’t do it anymore. Mr. Zhang threw me a bunch of .NET code: Study it yourself. Then he added another sentence Words: Use .NET to do it, you can get it done in just a few words, no need to worry about it.

Later I found that the previous paging process was to read the entire data set before doing paging processing. Once the amount of data is too large, , the processing will be very slow, or even the server crashes. Then the previous paging cannot be scrolled like a cursor, it is always fixed in a group, and it is impossible to achieve the effect of the current page number in the middle.

Let’s talk about it next. NET's paging control, it can indeed be solved in a few words, but the flaw is the first problem I found, which is that it is inefficient to read all the data and then process it, so I finally started to build ASP.NET purely by hand. High-performance paging.

The first is the stored procedure, which only takes out the data I need. If the number of pages exceeds the total number of data, it automatically returns the record of the last page:

set ANSI_NULLS ON 
set QUOTED_IDENTIFIER ON 
GO 
-- ============================================= 
-- Author: Clear 
-- Create date: 2007-01-30 
-- Description: 高性能分页 
-- ============================================= 
Alter PROCEDURE [dbo].[Tag_Page_Name_Select] 
-- 传入最大显示纪录数和当前页码 
    @MaxPageSize int, 
    @PageNum int, 
-- 设置一个输出参数返回总纪录数供分页列表使用 
    @Count int output 
AS 
BEGIN 
    SET NOCOUNT ON; 

   DECLARE 
-- 定义排序名称参数 
        @Name nvarchar(50), 
-- 定义游标位置 
        @Cursor int 
-- 首先得到纪录总数 
   Select @Count = count(tag_Name) 
     FROM [viewdatabase0716].[dbo].[view_tag]; 
-- 定义游标需要开始的位置 
    Set @Cursor = @MaxPageSize*(@PageNum-1)+1 
-- 如果游标大于纪录总数将游标放到最后一页开始的位置 
    IF @Cursor > @Count 
    BEGIN 
-- 如果最后一页与最大每次纪录数相等,返回最后整页 
        IF @Count % @MaxPageSize = 0 
            Set @Cursor = @Count - @MaxPageSize + 1 
-- 否则返回最后一页剩下的纪录 
        ELSE 
            Set @Cursor = @Count - (@Count % @MaxPageSize) + 1 
    END 
-- 将指针指到该页开始 
    Set Rowcount @Cursor 
-- 得到纪录开始的位置 
    Select @Name = tag_Name 
     FROM [viewdatabase0716].[dbo].[view_tag] 
    orDER BY tag_Name; 
-- 设置开始位置 
    Set Rowcount @MaxPageSize 
-- 得到该页纪录 
        Select *  
        From [viewdatabase0716].[dbo].[view_tag] 
        Where tag_Name >= @Name 
        order By tag_Name 

    Set Rowcount 0 
END

Then there is the paging control (... is the omitted method of generating HTML code):

using System.Data; 
using System.Configuration; 
using System.Web; 
using System.Web.Security; 
using System.Web.UI; 
using System.Web.UI.WebControls; 
using System.Web.UI.WebControls.WebParts; 
using System.Web.UI.HtmlControls; 
using System.Text; 

/// <summary> 
/// 扩展连接字符串 
/// </summary> 
public class ExStringBuilder 
{ 
    private StringBuilder InsertString; 
    private StringBuilder PageString; 
    private int PrivatePageNum = 1; 
    private int PrivateMaxPageSize = 25; 
    private int PrivateMaxPages = 10; 
    private int PrivateCount; 
    private int PrivateAllPage; 
    public ExStringBuilder() 
    { 
        InsertString = new StringBuilder(""); 
    } 
    /// <summary> 
    /// 得到生成的HTML 
    /// </summary> 
    public string GetHtml 
    { 
        get 
        { 
            return InsertString.ToString(); 
        } 
    } 
    /// <summary> 
    /// 得到生成的分页HTML 
    /// </summary> 
    public string GetPageHtml 
    { 
        get 
        { 
            return PageString.ToString(); 
        } 
    } 
    /// <summary> 
    /// 设置或获取目前页数 
    /// </summary> 
    public int PageNum 
    { 
        get 
        { 
            return PrivatePageNum; 
        } 
        set 
        { 
            if (value >= 1) 
            { 
                PrivatePageNum = value; 
            } 
        } 
    } 
    /// <summary> 
    /// 设置或获取最大分页数 
    /// </summary> 
    public int MaxPageSize 
    { 
        get 
        { 
            return PrivateMaxPageSize; 
        } 
        set 
        { 
            if (value >= 1) 
            { 
                PrivateMaxPageSize = value; 
            } 
        } 
    } 
    /// <summary> 
    /// 设置或获取每次显示最大页数 
    /// </summary> 
    public int MaxPages 
    { 
        get 
        { 
            return PrivateMaxPages; 
        } 
        set 
        { 
            PrivateMaxPages = value; 
        } 
    } 
    /// <summary> 
    /// 设置或获取数据总数 
    /// </summary> 
    public int DateCount 
    { 
        get 
        { 
            return PrivateCount; 
        } 
        set 
        { 
            PrivateCount = value; 
        } 
    } 
    /// <summary> 
    /// 获取数据总页数 
    /// </summary> 
    public int AllPage 
    { 
        get 
        { 
            return PrivateAllPage; 
        } 
    } 
    /// <summary> 
    /// 初始化分页 
    /// </summary> 
    public void Pagination() 
    { 
        PageString = new StringBuilder(""); 
//得到总页数 
        PrivateAllPage = (int)Math.Ceiling((decimal)PrivateCount / (decimal)PrivateMaxPageSize); 
//防止上标或下标越界 
        if (PrivatePageNum > PrivateAllPage) 
        { 
            PrivatePageNum = PrivateAllPage; 
        } 
//滚动游标分页方式 
        int LeftRange, RightRange, LeftStart, RightEnd; 
        LeftRange = (PrivateMaxPages + 1) / 2-1; 
        RightRange = (PrivateMaxPages + 1) / 2; 
        if (PrivateMaxPages >= PrivateAllPage) 
        { 
            LeftStart = 1; 
            RightEnd = PrivateAllPage; 
        } 
        else 
        { 
            if (PrivatePageNum <= LeftRange) 
            { 
                LeftStart = 1; 
                RightEnd = LeftStart + PrivateMaxPages - 1; 
            } 
            else if (PrivateAllPage - PrivatePageNum < RightRange) 
            { 
                RightEnd = PrivateAllPage; 
                LeftStart = RightEnd - PrivateMaxPages + 1; 
            } 
            else 
            { 
                LeftStart = PrivatePageNum - LeftRange; 
                RightEnd = PrivatePageNum + RightRange; 
            } 
        } 

//生成页码列表统计 
        PageString.Append(...); 

        StringBuilder PreviousString = new StringBuilder(""); 
//如果在第一页 
        if (PrivatePageNum > 1) 
        { 
            ... 
        } 
        else 
        { 
            ... 
        } 
//如果在第一组分页 
        if (PrivatePageNum > PrivateMaxPages) 
        { 
            ... 
        } 
        else 
        { 
            ... 
        } 
        PageString.Append(PreviousString); 
//生成中间页 
        for (int i = LeftStart; i <= RightEnd; i++) 
        { 
//为当前页时 
            if (i == PrivatePageNum) 
            { 
                ... 
            } 
            else 
            { 
                ... 
            } 
        } 
        StringBuilder LastString = new StringBuilder(""); 
//如果在最后一页 
        if (PrivatePageNum < PrivateAllPage) 
        { 
            ... 
        } 
        else 
        { 
            ... 
        } 
//如果在最后一组 
        if ((PrivatePageNum + PrivateMaxPages) < PrivateAllPage) 
        { 
            ... 
        } 
        else 
        { 
            ... 
        } 
        PageString.Append(LastString); 
    } 
    /// <summary> 
    /// 生成Tag分类表格 
    /// </summary> 
    public void TagTable(ExDataRow myExDataRow) 
    { 
        InsertString.Append(...); 
    }

Calling method:

//得到分页设置并放入Session 
        ExRequest myExRequest = new ExRequest(); 
        myExRequest.PageSession("Tag_", new string[] { "page", "size" }); 
//生成Tag分页 
        ExStringBuilder Tag = new ExStringBuilder(); 
        //设置每次显示多少条纪录 
        Tag.MaxPageSize = Convert.ToInt32(Session["Tag_size"]); 
        //设置最多显示多少页码 
        Tag.MaxPages = 9; 
        //设置当前为第几页 
        Tag.PageNum = Convert.ToInt32(Session["Tag_page"]); 
        string[][] myNamenValue = new string[2][]{ 
            new string[]{"MaxPageSize","PageNum","Count"}, 
            new string[]{Tag.MaxPageSize.ToString(),Tag.PageNum.ToString()} 
        }; 
//调用存储过程 
        DataTable myDataTable = mySQL.BatchGetDB("Tag_Page_Name_Select", myNamenValue, "Count"); 
        Tag.DateCount = (int)mySQL.OutputCommand.Parameters["@Count"].Value; 
        Tag.Pagination(); 

        HeadPage.InnerHtml = FootPage.InnerHtml = Tag.GetPageHtml; 

        for (int i = 0, j = myDataTable.Rows.Count; i < j; i++) 
        { 
            Tag.TagTable(new ExDataRow(myDataTable.Rows[i])); 
        } 
        TagBox.InnerHtml = Tag.GetHtml;

The method of processing page numbers to Session is not provided, and it is not a big deal. Calling the stored procedure returns The parameters and recording methods are similar to the batch data operation methods I wrote before. You only need to define an output method.

At present, I think these codes will still have flaws, and they will be strengthened during the code review later in the project. , what I want to say is don’t be confused by those things that are dragged around. That will never improve yourself. You must do something with an attitude of knowing what is happening and why. Only then will it help yourself. It will be obvious.

For more articles related to ASP.NET high-performance paging code, please pay attention to 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
C# .NET in the Modern World: Applications and IndustriesC# .NET in the Modern World: Applications and IndustriesMay 08, 2025 am 12:08 AM

C#.NET is widely used in the modern world in the fields of game development, financial services, the Internet of Things and cloud computing. 1) In game development, use C# to program through the Unity engine. 2) In the field of financial services, C#.NET is used to develop high-performance trading systems and data analysis tools. 3) In terms of IoT and cloud computing, C#.NET provides support through Azure services to develop device control logic and data processing.

C# .NET Framework vs. .NET Core/5/6: What's the Difference?C# .NET Framework vs. .NET Core/5/6: What's the Difference?May 07, 2025 am 12:06 AM

.NETFrameworkisWindows-centric,while.NETCore/5/6supportscross-platformdevelopment.1).NETFramework,since2002,isidealforWindowsapplicationsbutlimitedincross-platformcapabilities.2).NETCore,from2016,anditsevolutions(.NET5/6)offerbetterperformance,cross-

The Community of C# .NET Developers: Resources and SupportThe Community of C# .NET Developers: Resources and SupportMay 06, 2025 am 12:11 AM

The C#.NET developer community provides rich resources and support, including: 1. Microsoft's official documents, 2. Community forums such as StackOverflow and Reddit, and 3. Open source projects on GitHub. These resources help developers improve their programming skills from basic learning to advanced applications.

The C# .NET Advantage: Features, Benefits, and Use CasesThe C# .NET Advantage: Features, Benefits, and Use CasesMay 05, 2025 am 12:01 AM

The advantages of C#.NET include: 1) Language features, such as asynchronous programming simplifies development; 2) Performance and reliability, improving efficiency through JIT compilation and garbage collection mechanisms; 3) Cross-platform support, .NETCore expands application scenarios; 4) A wide range of practical applications, with outstanding performance from the Web to desktop and game development.

Is C# Always Associated with .NET? Exploring AlternativesIs C# Always Associated with .NET? Exploring AlternativesMay 04, 2025 am 12:06 AM

C# is not always tied to .NET. 1) C# can run in the Mono runtime environment and is suitable for Linux and macOS. 2) In the Unity game engine, C# is used for scripting and does not rely on the .NET framework. 3) C# can also be used for embedded system development, such as .NETMicroFramework.

The .NET Ecosystem: C#'s Role and BeyondThe .NET Ecosystem: C#'s Role and BeyondMay 03, 2025 am 12:04 AM

C# plays a core role in the .NET ecosystem and is the preferred language for developers. 1) C# provides efficient and easy-to-use programming methods, combining the advantages of C, C and Java. 2) Execute through .NET runtime (CLR) to ensure efficient cross-platform operation. 3) C# supports basic to advanced usage, such as LINQ and asynchronous programming. 4) Optimization and best practices include using StringBuilder and asynchronous programming to improve performance and maintainability.

C# as a .NET Language: The Foundation of the EcosystemC# as a .NET Language: The Foundation of the EcosystemMay 02, 2025 am 12:01 AM

C# is a programming language released by Microsoft in 2000, aiming to combine the power of C and the simplicity of Java. 1.C# is a type-safe, object-oriented programming language that supports encapsulation, inheritance and polymorphism. 2. The compilation process of C# converts the code into an intermediate language (IL), and then compiles it into machine code execution in the .NET runtime environment (CLR). 3. The basic usage of C# includes variable declarations, control flows and function definitions, while advanced usages cover asynchronous programming, LINQ and delegates, etc. 4. Common errors include type mismatch and null reference exceptions, which can be debugged through debugger, exception handling and logging. 5. Performance optimization suggestions include the use of LINQ, asynchronous programming, and improving code readability.

C# vs. .NET: Clarifying the Key Differences and SimilaritiesC# vs. .NET: Clarifying the Key Differences and SimilaritiesMay 01, 2025 am 12:12 AM

C# is a programming language, while .NET is a software framework. 1.C# is developed by Microsoft and is suitable for multi-platform development. 2..NET provides class libraries and runtime environments, and supports multilingual. The two work together to build modern applications.

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool