public class EmployeeDAO
{
public EmployeeDAO()
{
//
// TODO: Add constructor logic here
//
}
public IQueryable BindEmployees(int startRowIndex, int maximumRows)
{
EmployeeInfoDataContext dbEmp = new EmployeeInfoDataContext();
var query = from emp in dbEmp.Employees
join dept in dbEmp.Departments
on emp.DeptID equals dept.DeptID
select new
{
EmpID = emp.EmpID,
EmpName = emp.EmpName,
Age = emp.Age,
Address = emp.Address,
DeptName = dept.DepartmentName
};
return query.Skip(startRowIndex).Take(maximumRows);
}
public int GetEmployeeCount()
{
EmployeeInfoDataContext dbEmp = new EmployeeInfoDataContext();
return (from emp in dbEmp.Employees
select emp).Count();
}
} |
| In the above code, the LINQ query that fetches the employee record uses join operator to get the department name from the Department table(Refer BindEmployees() method). We use Skip() and Take() operator to fetch the records that belongs to the current page. |
| Next, we will use the above methods to build the pager links with hyperlinks and bind the current page. |
| The below code does that, |
|
|
public partial class GVPagingUsingLINQ : System.Web.UI.Page
{
int PageSize = 2;
protected void Page_Load(object sender, EventArgs e)
{
EmployeeDAO daoEmp = new EmployeeDAO();
int TotalRows = daoEmp.GetEmployeeCount();
int CurrentPage;
bool res = int.TryParse(Request.QueryString["Page"], out CurrentPage);
if (!res)
{
CurrentPage = 1;
}
int PageCount = TotalRows / PageSize;
if (PageCount * PageSize != TotalRows)
{
PageCount = PageCount + 1;
}
HyperLink hplPage = null;
Literal ltSpace = null;
for (int i = 1; i <= PageCount; i++)
{
hplPage = new HyperLink();
ltSpace = new Literal();
ltSpace.Text = " ";
hplPage.Text = i.ToString();
//make the current page non clickable
if (CurrentPage != i)
{
hplPage.NavigateUrl = Request.CurrentExecutionFilePath + "?Page=" + i.ToString();
}
plPager.Controls.Add(hplPage);
plPager.Controls.Add(ltSpace);
}
int StartIndex = (CurrentPage - 1) * PageSize;
gvEmployee.DataSource = daoEmp.BindEmployees(StartIndex, PageSize);
gvEmployee.DataBind();
}
|
To have different page size, set a different value to the variable “PageSize” in the above code(i have set it as 2). Execute the page and see it in action. Refer the below figure. |
 |
| Next section, we will implement the 2nd part of this tutorial which will provide jump to a page feature using dropdownlist control. |
| Jump To a Page Using DropDownList control |
| In this scenario, we will list all the page numbers in a DropDownList control and will bind the current page records based on the dropdownlist selection. Refer the below figure, |
 |
| ASPX |
<div>
Jump To Page Number: <asp:DropDownList ID="ddlPage" runat="server" AutoPostBack="True">
</asp:DropDownList>
<asp:GridView ID="gvEmployee" runat="server">
</asp:GridView> </div> |
| You can download code for this tutorial. |
| |