Click here to Skip to main content
15,886,110 members
Articles / Database Development / SQL Server
Tip/Trick

Effective Paging Using LINQ (Sample Code)

Rate me:
Please Sign up or sign in to vote.
4.80/5 (10 votes)
13 Sep 2012CPOL1 min read 71.9K   1.4K   10   10
Binding Gridview (or any other data control) with effective paging using LINQ

Introduction

Binding gridview with paging using LINQ is a nice way to bind large amount of data with efficient speed. Two LINQ operators Skip and Take make this task very easy.

Background 

HOW DO WE ACHIEVE EFFECTIVE PAGING FROM LINQ ON SERVER SIDE ? 

If you are familiar with LINQ and its techniques, then you must read about Deferred Execution of LINQ. Deferred Execution in LINQ depicts that LINQ executes query when it is about to use, means when we are using var of LINQ, not when we write it. You can learn more about deferred execution here

Using the Code

Skip and Take operators allow you to only pull back the records you need. 

If you are not interested in reading this article, you can simply download the code from the link at the top of this article. There, you will get the sample code of this article.

We can achieve effective paging by the following methods:

  1. Stored procedure
  2. From LINQ 

In the simple example below, I am using a LinqDataSource and handling its onselecting method to create our LINQ query and achieving effective paging. Set AutoPage to false because I am writing code to handle paging ourselves. Also the PageSize property of the GridView control is being populated from a integer constant in the code-behind class. 

On Aspx Page

ASP.NET
<asp:gridview allowpaging="True" autogeneratecolumns="False" 
datasourceid="LinqDataSource1" id="GridView1" pagesize="<%# PAGE_SIZE %>" 
runat="server" width="276px">
        <columns>
            <asp:boundfield datafield="ProductID" headertext="PID" readonly="True" 
		sortexpression="ProductID">
            <asp:boundfield datafield="ProductName" headertext="ProductName" 
		readonly="True" sortexpression="ProductName">
            <asp:boundfield datafield="UnitPrice" headertext="UnitPrice" 
		readonly="True" sortexpression="UnitPrice">
            
        </asp:boundfield></asp:boundfield></asp:boundfield></columns>
        </asp:gridview>
        

        <asp:linqdatasource autopage="False" contexttypename="DataClassesDataContext" 
		entitytypename="" id="LinqDataSource1" onselecting="LinqDataSource1_Selecting" 
	runat="server" select="new (ProductID, ProductName, UnitPrice)" tablename="Products">
        </asp:linqdatasource>   

On Code Behind   

C#
DataClassesDataContext db = new DataClassesDataContext();
protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
    }
}
public const int PAGE_SIZE = 10;

protected void LinqDataSource1_Selecting(object sender, LinqDataSourceSelectEventArgs e)
{
    // LINQ query


    var query = from m in db.Products
                select m;

    // Set the total count
    // so GridView knows how many pages to create
    e.Arguments.TotalRowCount = query.Count();

    // Get only the rows we need for the page requested
    query = query.Skip(GridView1.PageIndex * PAGE_SIZE).Take(PAGE_SIZE);

    e.Result = query;
}

Download the sample code for LINQ effective paging and paging from the stored procedure.

If this tip is helpful, then don't forget to say thanks. 

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer
India India
I do believe life is to help others ... So here i am .. in my spare time i learn new things of programming and try to help people with my knowledge .
I'm an energetic, self-motivated and hard-working Developer and Information Technology Professional with experience in projects, website design and development.

Visit My Technical Blog

Comments and Discussions

 
QuestionThank You Pin
PramodhPulluri25-Feb-15 5:18
PramodhPulluri25-Feb-15 5:18 
AnswerRe: Thank You Pin
Sarvesh Kushwaha3-Mar-15 17:21
Sarvesh Kushwaha3-Mar-15 17:21 
QuestionGreat example...except.... Pin
Member 994421924-Apr-14 7:06
Member 994421924-Apr-14 7:06 
AnswerRe: Great example...except.... Pin
Sarvesh Kushwaha24-Apr-14 15:21
Sarvesh Kushwaha24-Apr-14 15:21 
GeneralThank You Pin
Anto Reegan15-Nov-13 2:04
Anto Reegan15-Nov-13 2:04 
GeneralRe: Thank You Pin
Sarvesh Kushwaha15-Nov-13 5:25
Sarvesh Kushwaha15-Nov-13 5:25 
QuestionThank you Pin
Silvio Roberto Ramos24-Oct-13 1:01
Silvio Roberto Ramos24-Oct-13 1:01 
AnswerRe: Thank you Pin
Sarvesh Kushwaha24-Oct-13 2:57
Sarvesh Kushwaha24-Oct-13 2:57 
Questionnice example Pin
Member 98749681-Mar-13 0:48
Member 98749681-Mar-13 0:48 
AnswerRe: nice example Pin
Sarvesh Kushwaha1-Mar-13 14:02
Sarvesh Kushwaha1-Mar-13 14:02 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.