In this blog you will find ASP.NET 3.5 articles and some code samples. These code samples are created by me and should be working. Thanks for visiting my blog! Happy Dot Netting

Wednesday, January 14, 2009

LINQ To SQL - Handling Database Paging

You can handle database paging through LINQ to SQL by using two methods 
Skip()—Enables you to skip a certain number of records.
Take()—Enables you to take a certain number of records.
Example is shown as below:
Add a Class file to project which would be added to APP_CODE folder.
For performing paging through LINQ to SQL, you would need to create a partial class Products having methods to select the records, record count and handle paging. This is shown below
Note: Please use required namespace as shown in picture for this code to work. 

Public partial class Products
{
    // Select method - selects all rows from product table
    public static IEnumerable Select()
    {
        MydbDataContext db1 = new MydbDataContext();
        return db1.Products;
    }
    
    //Select Paged Method - handles paging 
    public static IEnumerable SelectPaged(int startrowindex, int maximumrows)
    {
        return Select().Skip(startrowindex).Take(maximumrows);
    }
    
    //Count Method - return count
    public static int selectcount()
    {
        MydbDataContext db1 = new MydbDataContext();
        return db1.Products.Count();
    }
  }


Now add a gridview on defaulf.aspx. Allow paging and set page size = 5
Add an object data source. Set Enable paging = True, SelectMethod = SelectPaged and SelectCountMethod = selectcount, TypeName = Products. (You may perform this activity through wizard)


Set datasource of gridview = object data source. Execute the project to view the results. 5 rows would be visible in one page. You may click on link below to navigate to next five records. 

No comments: