Introduction

Why We Need To Use Custom Page Size And Paging

Stored Procedure For Paging

  1. SET ANSI_NULLS ON
  2. GO
  3. SET QUOTED_IDENTIFIER ON
  4. GO
  5. -- === === === === === === === === === === === === === === === CREATE PROCEDURE GetCustomersPageWise
  6. @PageIndex INT = 1,
  7. @PageSize INT = 10,
  8. @RecordCount INT OUTPUT
  9. AS
  10. BEGIN
  11. SET NOCOUNT ON;
  12. SELECT
  13. ROW_NUMBER() OVER(ORDER BY[CustomerID] ASC) AS RowNumber,
  14. [CustomerID],
  15. [CompanyName],
  16. [ContactName]
  17. INTO #Results FROM[Customers]

  18. SELECT @RecordCount = COUNT( * )
  19. FROM #Results
  20. SELECT *
  21. FROM #Results
  22. WHERE RowNumber BETWEEN(@PageIndex - 1) * @PageSize + 1
  23. AND(((@PageIndex - * @PageSize + 1) + @PageSize) - 1

  24. DROP TABLE #Results;
  25. END
  26. GO

HTML code

Sample ASP.NET Front end code for custom grid is given below.

C# Code

  1. private void GetGridDataPageWise(int pageIndex) {
  2. string constring = ConfigurationManager.ConnectionStrings["constring"].ConnectionString;
  3. using(SqlConnection con = new SqlConnection(constring)) {
  4. using(SqlCommand cmd = new SqlCommand("GetGridDataPageWise", con)) {
  5. cmd.CommandType = CommandType.StoredProcedure;
  6. cmd.Parameters.AddWithValue("@PageIndex", pageIndex);
  7. cmd.Parameters.AddWithValue("@PageSize", int.Parse(ddlPageSize.SelectedValue));
  8. cmd.Parameters.Add("@RecordCount", SqlDbType.Int, 4);
  9. cmd.Parameters["@RecordCount"].Direction = ParameterDirection.Output;
  10. con.Open();
  11. IDataReader idr = cmd.ExecuteReader();
  12. GridView1.DataSource = idr;
  13. GridView1.DataBind();
  14. idr.Close();
  15. con.Close();
  16. int recordCount = Convert.ToInt32(cmd.Parameters["@RecordCount"].Value);
  17. this.GetGridDataBasedonPageIndex(recordCount, pageIndex);
  18. }
  19. }
  20. }
  21. private void GetGridDataBasedonPageIndex(int recordCount, int currentPage) {
  22. double dblPageCount = (double)((decimal) recordCount / decimal.Parse(ddlPageSize.SelectedValue));
  23. int pageCount = (int) Math.Ceiling(dblPageCount);
  24. List < ListItem > pages = new List < ListItem > ();
  25. if (pageCount > 0) {
  26. pages.Add(new ListItem("First", "1", currentPage > 1));
  27. for (int i = 1; i <= pageCount; i++) {
  28. pages.Add(new ListItem(i.ToString(), i.ToString(), i != currentPage));
  29. }
  30. pages.Add(new ListItem("Last", pageCount.ToString(), currentPage < pageCount));
  31. }
  32. rptPager.DataSource = pages;
  33. rptPager.DataBind();
  34. }
  35. protected void PageSize_Changed(object sender, EventArgs e) {
  36. this.GetGridDataPageWise(1);
  37. }
  38. protected void Page_Changed(object sender, EventArgs e) {
  39. int pageIndex = int.Parse((sender as LinkButton).CommandArgument);
  40. this.GetGridDataPageWise(pageIndex);
  41. }
Example

page

Advantage