Using LINQ to Create a Pager for SQL Data in C#


Server Intellect


Using LINQ to Create a Pager for SQL Data in C#

This tutorial was created with Microsoft Visual Studio .NET 2008. However, if you are using 2005, you can implement LINQ by downloading Microsoft's LINQ Community Technology Preview release from here.

Server Intellect assists companies of all sizes with their hosting needs by offering fully configured server solutions coupled with proactive server management services. Server Intellect specializes in providing complete internet-ready server solutions backed by their expert 24/365 proactive support team.

Using LINQ to SQL, we can make use of the built-in methods to page the database data a lot easier than with using SQL alone. LINQ to SQL can make it extremely easy for us to create pages from our data source using just two methods - Skip and Take.
Skip allows us to skip a certain number of records, and Take allows us to select a certain number of records.

In this tutorial, we will be creating a SQL database and adding a LINQ to SQL Class that Visual Studio creates to represent our database. We will then extend the class to support paging of the data, using the methods mentioned above.
Let's start by creating our database. In this example, we will use one table named tblEmployees with three columns - id, name, position.
Once the database is set up, we will add some sample data - we will need at least 5 records to make use of the paging feature.

Once we have our database set up and have added data to it, we then need to create a representation of our database using a LINQ to SQL Class. Right-click your project in the Solution Explorer, and goto Add ASP.NET Folder > App_Code. Now right-click the App_Code folder and choose Add New Item.. LINQ to SQL Classes. This will bring up the Object Relationship Designer. All we need to do here is drag the tables we will be working with into the Designer, from the Server Explorer, and then Save. This will allow Visual Studio to create a representation of our database. For this example, we will name it Employees.dbml

Now we will create an extension of this class by again right-clicking the App_Code folder and choose Add New Item.. Class. We will also name this Employees and change the public class to public partial class. We may need to also add extra assembly references; we will be using the System.Collections.Generic, System.Data.Linq and System.Linq in particular.
We are going to extend this class by providing methods to select the data in pages. Our first method will select all the data:

public static IEnumerable<tblEmployee> Select()
{
EmployeesDataContext db = new EmployeesDataContext();
return db.tblEmployees;
}

Notice the EmployeesDataContext refers to our LINQ to SQL class.
Next, we add a method to move between the pages of the data:

public static IEnumerable<tblEmployee> SelectPage(int startRowIndex, int maximumRows)
{
return Select().Skip(startRowIndex).Take(maximumRows);
}

If you're looking for a really good web host, try Server Intellect - we found the setup procedure and control panel, very easy to adapt to and their IT team is awesome!

This method will be called when a new page is requested through PostBack. The GridView's paging links will provide the variables required for this method.
Finally, we create a method that will get the number of records in the database:

public static int SelectCount()
{
return Select().Count();
}

The entire class extension will look something like this:

using System;
using System.Data;
using System.Configuration;
using System.Linq;
using System.Data.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Collections.Generic;

/// <summary>
/// Extension class for Employees.dbml
/// </summary>
public partial class Employees
{
public static IEnumerable<tblEmployee> Select()
{
EmployeesDataContext db = new EmployeesDataContext();
return db.tblEmployees;
}

public static IEnumerable<tblEmployee> SelectPage(int startRowIndex, int maximumRows)
{
return Select().Skip(startRowIndex).Take(maximumRows);
}

public static int SelectCount()
{
return Select().Count();
}
}

We used over 10 web hosting companies before we found Server Intellect. Their dedicated servers and add-ons were setup swiftly, in less than 24 hours. We were able to confirm our order over the phone. They respond to our inquiries within an hour. Server Intellect's customer support and assistance are the best we've ever experienced.

Now we are done with the class, and can implement the functionality into our ASPX page. To make this work, we will need to use a GridView control and an ObjectDataSource:

<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server" />

<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:GridView ID="DataGrid1" runat="server" Width="400px" />

<asp:ObjectDataSource ID="ObjectDataSource1" runat="server" />
</ContentTemplate>
</asp:UpdatePanel>
</form>

Because we are using VS.NET 2008, we can simply add AJAX Functionality to our web application using a ScriptManager and UpdatePanel.
In order to implement paging, we need to set the EnablePaging attributes on both of our controls. We also set the Method attributes of the ObjectDataSource to reflect those we created in our partial class - note that the TypeName refers to our class name.
NOTE: We can change the PageSize to set the number of items on each page.

<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server" />

<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:GridView ID="DataGrid1" runat="server"
AllowPaging="true" PageSize="5" DataSourceID="ObjectDataSource1"
Width="400px" />

<asp:ObjectDataSource ID="ObjectDataSource1" runat="server"
TypeName="Employees" SelectMethod="SelectPage"
SelectCountMethod="SelectCount" EnablePaging="true" />
</ContentTemplate>
</asp:UpdatePanel>
</form>

If you're ever in the market for some great Windows web hosting, try Server Intellect. We have been very pleased with their services and most importantly, technical support.

Download Project Source - Enter your Email to be emailed a link to download the Full Source Project used in this Tutorial!



100% SPAM FREE! We will never sell or rent your email address!
 


Comments
Fred said:

This is a great tutorial - there are LINQ to SQL webcasts on www.microsoft.com/.../msdnvs2008.aspx that I've looked at, too. Thanks!

Posted 03/06/2009 at 11:58 AM
how to play craps in a casino said:

I 'll be posting about the validation logic shortly. You should be able to perform the conditional logic you are after to check whether and order (or its order items) are already in the database prior to completing the transaction.

Thanks

Posted 06/29/2009 at 5:04 AM
sravan said:

i didnt get the output result i got the error that objecrdate source is not valid

Posted 11/07/2009 at 5:52 AM
Shankar said:

Nice site

Posted 02/15/2010 at 4:53 AM
Shankar said:

Nice article

Posted 02/15/2010 at 4:55 AM
Call Center Software said:

As LINQ is a recently developed technology it is not familiar to all. Even though became important in software development field (web applications) as it have so many advantages from the conventional data querying techniques used in ASP .NET. This article is a tutorial about LINQ querying technique. It is about how LINQ can be used to create a pager for SQL data in C#. The author has also given the source from which we can download LINQ which is very useful to us. In this tutorial he describes about how SQL database is created and how a LINQ is added to SQL class that Visual Studio creates to represent the database. He did all these explanations with the help of an example and that made it easy to understand by others. Also he provided a facility to download the full source code of the project related with this topic and it is very much useful for computer students to evaluate and study the technique.

Posted 05/06/2010 at 12:03 PM
gambling freerolls said:

ive been playing around with linq to sql, simply love it.just that your example takes it in the layers approach where the data layer is not in the same page as presentation, also i was not familiar thats we could do all that via obj data source.

Posted 07/16/2010 at 5:51 AM
bad credit auto loan said:

Visual Basic developers had to implement a Custom Event or another workaround when their types needed to expose an Event and they had to be Serializable. C# had this capability, now Visual Basic does too!..

Visual Basic developers can now decorate the Event with the NonSerialized attribute.

Posted 07/19/2010 at 6:35 AM
matchmaking said:

We use a CTE wrapped in Dynamic SQL (because our application requires dynamic sorting of data server side) within a stored procedure. I can provide a basic example if you'd like.

I haven't had a chance to look at the T/SQL that LINQ produces. Can someone post a sample?

We don't use LINQ or straight access to the tables as we require the extra layer of security (granted the dynamic SQL breaks this somewhat).

Posted 07/21/2010 at 9:26 PM
junk yards said:

Which approach is faster: Pro*C, SQL or PL/SQL? The problem: I have to move data from one table to another, and I have three options:

1. Using Pro*C to open a cursor, fetch each row and insert it in another table.

2. Using SQL which will be like

Insert into table2

values( select * from

table1)

Posted 07/22/2010 at 2:12 PM
online bingo said:

This article gives the light in which we can observe the reality. this is very nice one and gives in depth information. thanks for this nice article Good post.....Valuable information for all.I will recommend my friends to read this for sure…

Posted 08/16/2010 at 8:09 AM
fico score said:

I can’t use standard Pager implementation because AsPagination(…) creates LazyPagination instance which converts the IEnumerable to IQueryable and when grid start to iterate over the items, it’s the grid who gives an hint to go for data through LazyPagination.

I use NHibernate to get the data, so I can’t use the LazyPagination – in my case it’s the controller who gives the impuls to load the data a prepare the model. In IPagination case it’s in the rendering phase.

I think IPagination is fine but I was thinking to implement it as a CustomPagination instead of LazyPaginantion.

Jeremy, what do u think?

Posted 08/19/2010 at 9:30 PM
fico score said:

You use SQL backup and restore. before you do that, though, you need to do a few admin tasks, first. First, you need to shrink your log space, next create a backup device, and finally, backup your database.

Posted 08/21/2010 at 2:42 PM
coach outlet said:

[System.Data.Linq.Mapping.DatabaseAttribute(Name="Database")]

public partial class DataClassesDataContext : System.Data.Linq.DataContext

{

Posted 08/26/2010 at 8:05 AM
louis vuitton bags said:

thank you for sharing

Posted 08/26/2010 at 8:05 AM
UGG Bailey Button Triplet said:

<p>We've updated the traditional style of our <b><a href="http://www.uggboots5815.com/">UGG Classic Tall</a></b> with wooden <strong>UGG? logo buttons</strong> and elastic band closures. The <b><a href="http://www.uggboots5815.com/ugg-bailey-button-triplet-c-95.html">women's Bailey Button Triplet</a></b> can either be worn up or cuffed down adding a little variety depending on your style. All new UGG boots in our <b><a href="http://www.uggboots5815.com/ugg-bailey-button-triplet-c-95.html">Classic Bailey</a></b> Collection feature a soft foam insole covered with genuine sheepskin and have a molded EVA light and flexible outsole designed for amazing comfort with every step. <strong>Always free shipping,and almost need 5-7 days deliver to your door</strong>.</p>

<a href="http://www.uggboots5815.com/ugg-bailey-button-triplet-c-95.html"><h1>UGG Bailey Button Triplet</h1></a>

Posted 08/26/2010 at 8:05 AM
chanel purses & chanel bags & chanel handbags said:

<a href="http://www.chanelsonline.com/"title="chanel purses"><h1>chanel purses</h1></a>

<a href="http://www.chanelsonline.com/"title="chanel bags"><h1>chanel bags</h1></a>

<a href="http://www.chanelsonline.com/"title="chanel handbags"><h1>chanel handbags</h1></a>

<a href="http://www.chanelsonline.com/"title="chanel coco"><h1>chanel coco</h1></a>

<a href="http://www.chanelsonline.com/chanel-j12-watches-c-96.html"title="chanel watches & chanel watch & chanel j12 watches"><h1>chanel watches & chanel watch & chanel j12 watches</h1></a>

<a href="http://www.chanelsonline.com/chanel-sunglasses-c-99.html"title="chanel sunglasses & chanel sunglass"><h1>chanel sunglasses & chanel sunglass</h1></a>

Posted 08/26/2010 at 8:06 AM
louis vuitton bags & lv handbags & louis vuitton & lv said:

else

{

textBox3.Enabled = true;

button4.Text = "Disable >>";

Posted 08/26/2010 at 8:13 AM

Posted 08/26/2010 at 8:14 AM
UGG Bailey Button & UGG Bailey Button Boots said:

handlers by clicking on the Events button in the Properties window, and then double-clicking on both of the MouseHover and MouseLeave events.

Let's start with the statusstrip label.Thanks

Posted 08/26/2010 at 8:17 AM
MBT Shoes Sale said:

cocokathy90

Posted 08/26/2010 at 8:19 AM
gucci bags said:

cocokathy90

Posted 08/26/2010 at 8:19 AM
Supra Shoes said:

cocokathy

Posted 08/26/2010 at 8:20 AM
UGG Bailey Button Triplet said:

handlers by clicking on the Events button in the Properties window, and then double-clicking on both of the MouseHover and MouseLeave events.

Posted 08/26/2010 at 8:20 AM
louis vuitton handbags said:

cocokathy

Posted 08/26/2010 at 8:20 AM
chanel handbags said:

coockathy90

Posted 08/26/2010 at 8:21 AM
ugg classic boots & womens ugg boots said:

the MouseHover and MouseLeave events.

Posted 08/26/2010 at 8:23 AM
ugg classic boots & ugg boots said:

the MouseHover and MouseLeave events.

Posted 08/26/2010 at 8:24 AM
ugg classic boots & ugg boots & ugg classic tall & ugg classic tall boots said:

with the statusstrip label.Thanks

Posted 08/26/2010 at 8:27 AM
ugg classic boots & ugg boots & ugg classic tall & ugg classic tall boots said:

textBox3.Enabled = true;

button4.Text = "Disable >>";

Posted 08/26/2010 at 8:13 AM

Posted 08/26/2010 at 8:28 AM
gucci handbags said:
Posted 08/26/2010 at 9:12 PM

Leave a Comment