Skip to main content

Custom paging in asp.net using stored procedure in gridview

When we need to display only some of the record in page and table in database contains lacks of rows then   we should have to use custom paging instead of default paging.

Why to avoid default paging and use custom paging reason -

  •  In default paging we are fetching all rows in database that takes more execution time (i.e query    execution time in SQL Server or any database management system).
  •   In default paging all rows (records of table) load in memory so memory consumption
  •   In default paging all rows fetch form back end to front end but we are displaying only some of the rows i.e page-size.

How to do custom paging -

  • Need to customize you store procedure 
  • No Change in binding Gridview or Datalist or Repeater whatever you are using 
  • Need to populate ( Generate ) Pager (Pagination ) manually ( Code also given below). 

Store Procedure Code :


CREATE PROCEDURE getDeals
      @StartIndex int,
      @PageSize int,
      @TotalCount int OutPut
as

select @TotalCount=count(1) from mstrDeals;
WITH CTE AS
(
   select top(@startIndex+@PageSize-1) ROW_NUMBER() OVER(ORDER BY creationdate) RowNumber,dealid,dealTitle
   from mstrDeals
)
select * from CTE where RowNumber between @startIndex and (@startIndex+@PageSize-1)


Binding Grid Control Code :


public void bindGrid(int currentPage)
{
 int pageSize = 10;
 int _TotalRowCount = 0;

 string _ConStr = ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
 using (SqlConnection con = new SqlConnection(_ConStr))
 {

   SqlCommand cmd = new SqlCommand("getDeals", con);
   cmd.CommandType = CommandType.StoredProcedure;

   int startRowNumber = ((currentPage - 1) * pageSize) + 1;
      
   cmd.Parameters.AddWithValue("@StartIndex", startRowNumber);
   cmd.Parameters.AddWithValue("@PageSize", pageSize);

   SqlParameter parTotalCount = new SqlParameter("@TotalCount", SqlDbType.Int);
   parTotalCount.Direction = ParameterDirection.Output;
   cmd.Parameters.Add(parTotalCount);

   SqlDataAdapter da = new SqlDataAdapter(cmd);
   DataSet ds = new DataSet();
   da.Fill(ds);

   _TotalRowCount = Convert.ToInt32(parTotalCount.Value);

   grdCustomPagging.DataSource = ds;
   grdCustomPagging.DataBind();

   generatePager(_TotalRowCount, pageSize, currentPage);

 }
}


<asp:GridView Width="500" runat="server" ID="grdCustomPagging">
</asp:GridView>


Then we need to generate pager with total no of rows, page size and current page, below is the sample code that populating pager here total number of pager links is 5 that can be customize further by resetting local variable named totalLinkInPage and have first and last button also which automatic enable or disable when current page is first or last accordingly.

Generate Pager Code :


public void generatePager(int totalRowCount, int pageSize, int currentPage)
{
  int totalLinkInPage = 5;
  int totalPageCount = (int)Math.Ceiling((decimal)totalRowCount / pageSize);

  int startPageLink = Math.Max(currentPage - (int)Math.Floor((decimal)totalLinkInPage / 2), 1);
  int lastPageLink = Math.Min(startPageLink + totalLinkInPage - 1, totalPageCount);

  if ((startPageLink + totalLinkInPage - 1) > totalPageCount)
  {
      lastPageLink = Math.Min(currentPage + (int)Math.Floor((decimal)totalLinkInPage / 2), totalPageCount);
      startPageLink = Math.Max(lastPageLink - totalLinkInPage + 1, 1);
  }

  List<ListItem> pageLinkContainer = new List<ListItem>();

  if (startPageLink != 1)
      pageLinkContainer.Add(new ListItem("First", "1", currentPage != 1));
  for (int i = startPageLink; i <= lastPageLink; i++)
  {
      pageLinkContainer.Add(new ListItem(i.ToString(), i.ToString(), currentPage != i));
  }
  if (lastPageLink != totalPageCount)
      pageLinkContainer.Add(new ListItem("Last", totalPageCount.ToString(), currentPage != totalPageCount));

  dlPager.DataSource = pageLinkContainer;
  dlPager.DataBind();
}

protected void dlPager_ItemCommand(object source, DataListCommandEventArgs e)
{
   if (e.CommandName == "PageNo")
   {
       bindGrid(Convert.ToInt32(e.CommandArgument));
   }
}


<asp:DataList CellPadding="5" RepeatDirection="Horizontal" runat="server" ID="dlPager"
    onitemcommand="dlPager_ItemCommand">
    <ItemTemplate>
       <asp:LinkButton Enabled='<%#Eval("Enabled") %>' runat="server" ID="lnkPageNo" Text='<%#Eval("Text") %>' CommandArgument='<%#Eval("Value") %>' CommandName="PageNo"></asp:LinkButton>
    </ItemTemplate>
</asp:DataList>

Custom paging in asp.net using stored procedure in gridview Demo

Custom paging in asp.net c# store procedure with pagination
Custom paging in asp.net using stored procedure in gridview


Popular posts from this blog

Regular expression for alphanumeric with space in asp.net c#

How to validate that string contains only alphanumeric value with some spacial character and with whitespace and how to validate that user can only input alphanumeric with given special character or space in a textbox (like name fields or remarks fields). In remarks fields we don't want that user can enter anything, user can only able to enter alphanumeric with white space and some spacial character like -,. etc if you allow. Some of regular expression given below for validating alphanumeric value only, alphanumeric with whitspace only and alphanumeric with whitespace and some special characters.

How to handle click event of linkbutton inside gridview

Recently I have posted how to sort only current page of gridview , Scrollble gridview with fixed header through javascript , File upload control inside gridview during postback and now i am going to explain how to handle click event of linkbutton or any button type control inside gridview. We can handle click event of any button type control inside gridview by two way first is through event bubbling and second one is directly (in this type of event handling we need to access current girdviewrow container)

regex - check if a string contains only alphabets c#

How to validate that input string contains only alphabets, validating that textbox contains only alphabets (letter), so here is some of the ways for doing such task. char have a property named isLetter which is for checking if character is a letter or not, or you can check by the regular expression  or you can validate your textbox through regular expression validator in asp.net. Following code demonstrating the various ways of implementation.

How to validate dropdownlist in JavaScript

In this article you will see how to put validation in dropdownlist by javascript, suppose first item value of dropdownlist is 0 and text is "-Select-" just like given below and we have to validate that at least one item is selected excluding default i.e "-Select-".

Refreshing page in Javascript

In this article we will see that how to refresh or reload a page through Java Script there are a lot of ways to refresh or reload a document depending how we want (from server side