Sunday, August 11, 2019

How to implement Custom Paging and Sorting in ASP.Net Gridview

Displaying data in ASP.NET Webform is very simple task using GridView with some great (default) functionality like sorting and paging. We can use Gridview's default paging by setting it's property AllowPaging="true" and sotring by setting AllowSorting="True". The GridView will show the pager itself depending on the PageSize and total records. But this way is very tedious and degrades the performance of the application because everytime the PageIndex changes, the GridView will be bound with the complete datasource that is not required at all, as we need to show only data to the corresponding PageIndex. To improve the performance of the web application I am going to explain how to implement custom paging and oorting in ASP.Net GridView. 

Steps :

Step - 1 : Create New Project.

Go to File > New > Project > Select asp.net web forms application > Entry Application Name > Click OK.

Step-2: Add a Database.

Go to Solution Explorer > Right Click on App_Data folder > Add > New item > Select SQL Server Database Under Data > Enter Database name > Add.

Step-3: Create table for stote data.

Open Database > Right Click on Table > Add New Table > Add Columns > Save > Enter table name > Ok. 
In this example, I have used one tables as below 

Step-4: Add Entity Data Model.

Go to Solution Explorer > Right Click on Project name form Solution Explorer > Add > New item > Select ADO.net Entity Data Model under data > Enter model name > Add.
A popup window will come (Entity Data Model Wizard) > Select Generate from database > Next >

Chose your data connection > select your database > next > Select tables > enter Model Namespace > Finish. 

Step-5: Add Reference of System.Linq.Dynamic

Right Click on References > Manage NuGet Packages > Seach online with "System.Linq.Dynamic" keyword > Select & install System.Linq.Dynamic

Step-6: Add a Webpage and Design for Show Data in Gridview With Custom Paging and Sorting option.

Go to Solution Explorer > Right Click on Project name form Solution Explorer > Add > New item > Select web form/ web form using master page under Web > Enter page name > Add.

Step-7: Write method for fetch query string value.

Please write following code... 
  1. private string QueryStringValue(string name)
  2. {
  3. return Request.QueryString[name] != null ? Request.QueryString[name].ToString() : "";
  4. }

Step-8: Write method for Generate gridview sort link.

Please write following code... 
  1. protected string GetSortLink(string dataField)
  2. {
  3. string link = "";
  4. string sortname = QueryStringValue("sortname");
  5. string sortdir = QueryStringValue("sortdir");
  6. link += "sortname=" + dataField;
  7. if (sortname.Equals(dataField, StringComparison.CurrentCultureIgnoreCase))
  8. {
  9. if (sortdir.Equals("asc", StringComparison.CurrentCultureIgnoreCase))
  10. {
  11. link += "&sortdir=desc";
  12. }
  13. else
  14. {
  15. link += "&sortdir=asc";
  16. }
  17. }
  18. else
  19. {
  20. link += "&sortdir=asc";
  21. }
  22. return link;
  23. }

Step-9: Write method for Generate Paging Link

Please write following code... 
  1. protected string GetPageLink(int noOfPage)
  2. {
  3. string link = "";
  4. StringBuilder sb = new StringBuilder();
  5. bool hasPage = Request.QueryString["page"] != null ? true : false;
  6. string currentPage = hasPage ? QueryStringValue("page") : "1";
  7. for (int i = 1; i < noOfPage +1; i++)
  8. {
  9. if (currentPage == i.ToString())
  10. {
  11. sb.AppendLine(string.Format("<span>{0}</span>",i));
  12.  
  13. }
  14. else if (hasPage)
  15. {
  16. sb.AppendLine(string.Format("<a href={0}>{1}</a>", Request.RawUrl.ToLower().Replace("page=" + currentPage, "page=" + i), i));
  17. }
  18. else
  19. {
  20. sb.AppendLine(string.Format("<a href='{0}{1}{2}'>{3}</a>", Request.RawUrl,
  21. Request.RawUrl.ToString().Contains('?') ? "&" : "?", ("page=" + i), i));
  22. }
  23. }
  24. link = sb.ToString();
  25. return link;
  26. }

Step-10: Design the added webpage for show data in Gridview with Paging and sorting functionality.

HTML Code 
  1. <%@ Page Title="" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="MyGrid.aspx.cs" Inherits="ASPGridPagingSorting.MyGrid" %>
  2. <asp:Content ID="Content1" ContentPlaceHolderID="HeadContent" runat="server">
  3. </asp:Content>
  4. <asp:Content ID="Content2" ContentPlaceHolderID="FeaturedContent" runat="server">
  5. </asp:Content>
  6. <asp:Content ID="Content3" ContentPlaceHolderID="MainContent" runat="server">
  7.  
  8. <%-- I would like to add some css for looks good --%>
  9. <style>
  10. .myGrid th a.asc:after {
  11. content: ' ⇣';
  12. }
  13. .myGrid th a.desc:after {
  14. content: ' ⇡';
  15. }
  16.  
  17. .myGrid {
  18. background-color: #fff;
  19. margin: 5px 0 10px 0;
  20. border: solid 1px #c1c1c1;
  21. border-collapse:collapse;
  22. }
  23. .myGrid td {
  24. padding: 2px;
  25. border: solid 1px #c1c1c1;
  26. color: #717171;
  27. padding:5px;
  28. }
  29. .myGrid th a {
  30. font-size:12pt;
  31. padding:5px;
  32. }
  33. .pager a,.pager span{
  34. padding: 5px 10px;
  35. border: 1px solid #3F3F3F;
  36. background-color: #938F8F;
  37. display: inline-block;
  38. text-decoration: none;
  39. color: #fff;
  40. }
  41. .pager span {
  42. color: black !important;
  43. background-color: #f4f4f4 !important;
  44. }
  45. .myGrid th{
  46. color: #fff;
  47. background-color: #E2E2E2;
  48. border-left: solid 1px #c1c1c1;
  49. font-size: 0.9em;
  50. }
  51. .myGrid .alt {
  52. background-color: #EFEFEF;
  53. }
  54. </style>
  55.  
  56. <div>
  57. <%-- Grid --%>
  58. <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" CssClass="myGrid"
  59. AllowPaging="true" AllowSorting="true" Width="900px">
  60.  
  61. <Columns>
  62. <asp:TemplateField>
  63. <ItemTemplate><%#Eval("SLID") %></ItemTemplate>
  64. <HeaderTemplate>
  65. <asp:HyperLink runat="server" CssClass='<%#hfSortName.Value.ToLower() == "slid"? hfSortDir.Value.ToLower() : "" %>'
  66. Text="SL ID" NavigateUrl='<%#string.Format("/MyGrid.aspx?{0}",GetSortLink("SLID")) %>'>SL ID</asp:HyperLink>
  67. </HeaderTemplate>
  68. </asp:TemplateField>
  69.  
  70. <asp:TemplateField>
  71. <ItemTemplate><%#Eval("Rank") %></ItemTemplate>
  72. <HeaderTemplate>
  73. <asp:HyperLink ID="HyperLink1" runat="server" CssClass='<%#hfSortName.Value.ToLower() == "rank"? hfSortDir.Value.ToLower() : "" %>'
  74. Text="Rank" NavigateUrl='<%#string.Format("/MyGrid.aspx?{0}",GetSortLink("rank")) %>'>Rank</asp:HyperLink>
  75. </HeaderTemplate>
  76. </asp:TemplateField>
  77.  
  78. <asp:TemplateField>
  79. <ItemTemplate><%#Eval("CompanyName") %></ItemTemplate>
  80. <HeaderTemplate>
  81. <asp:HyperLink ID="HyperLink1" runat="server" CssClass='<%#hfSortName.Value.ToLower() == "companyname"? hfSortDir.Value.ToLower() : "" %>'
  82. Text="Company Name" NavigateUrl='<%#string.Format("/MyGrid.aspx?{0}",GetSortLink("CompanyName")) %>'>Company Name</asp:HyperLink>
  83. </HeaderTemplate>
  84. </asp:TemplateField>
  85. <asp:TemplateField>
  86. <ItemTemplate><%#Eval("Revenue") %></ItemTemplate>
  87. <HeaderTemplate>
  88. <asp:HyperLink ID="HyperLink1" runat="server" CssClass='<%#hfSortName.Value.ToLower() == "revenue"? hfSortDir.Value.ToLower() : "" %>'
  89. Text="Revenue" NavigateUrl='<%#string.Format("/MyGrid.aspx?{0}",GetSortLink("Revenue")) %>'>Revenue</asp:HyperLink>
  90. </HeaderTemplate>
  91. </asp:TemplateField>
  92. <asp:TemplateField>
  93. <ItemTemplate><%#Eval("Industry") %></ItemTemplate>
  94. <HeaderTemplate>
  95. <asp:HyperLink ID="HyperLink1" runat="server" CssClass='<%#hfSortName.Value.ToLower() == "industry"? hfSortDir.Value.ToLower() : "" %>'
  96. Text="Industry" NavigateUrl='<%#string.Format("/MyGrid.aspx?{0}",GetSortLink("Industry")) %>'>Industry</asp:HyperLink>
  97. </HeaderTemplate>
  98. </asp:TemplateField>
  99. </Columns>
  100.  
  101. </asp:GridView>
  102. </div>
  103. <div class="pager">
  104. <%-- Paging --%>
  105. <asp:Literal ID="l1Pagger" runat="server"></asp:Literal>
  106. </div>
  107. <div>
  108. <%-- Hidden fileds --%>
  109. <asp:HiddenField ID="hfCurrentPage" runat="server" Value="0" />
  110. <asp:HiddenField ID="hfSortName" runat="server" Value="" />
  111. <asp:HiddenField ID="hfSortDir" runat="server" Value="" />
  112. </div>
  113. </asp:Content>
  114.  

Step-11: Write method (in the code behind) for Populate data from database and bind to gridview.

Please write following code... 
  1. private void populate(int rowPerPage)
  2. {
  3. int pageNo = 0;
  4. int totalPage = 0;
  5. //Fetch data from URL
  6. string sortName = string.IsNullOrEmpty(QueryStringValue("sortname")) ? "slid" : QueryStringValue("sortname");
  7. string sortDir = string.IsNullOrEmpty(QueryStringValue("sortdir")) ? "asc" : QueryStringValue("sortdir");
  8. int.TryParse(QueryStringValue("page"), out pageNo);
  9.  
  10. //set current values
  11. pageNo = pageNo == 0 ? 1 : pageNo;
  12. hfCurrentPage.Value = pageNo.ToString();
  13. hfSortName.Value = sortName;
  14. hfSortDir.Value = sortDir;
  15. //Fetch data from Server
  16. using (MyDatabaseEntities dc = new MyDatabaseEntities())
  17. {
  18. int totalRecord = dc.TopCompanies.Count();
  19. totalPage = (totalRecord / rowPerPage) + ((totalRecord % rowPerPage) > 0 ? 1 : 0);
  20. var v = dc.TopCompanies.OrderBy(sortName + " " + sortDir).Skip((pageNo - 1) * rowPerPage).Take(rowPerPage).ToList();
  21. GridView1.DataSource = v;
  22. GridView1.DataBind();
  23. }
  24. //Generate Pager link
  25. l1Pagger.Text = GetPageLink(totalPage);
  26. }

Step-12: Write following code in the page load event for load data in gridview.

Please write following code... 
  1. protected void Page_Load(object sender, EventArgs e)
  2. {
  3. if (!IsPostBack)
  4. {
  5. int pageSize = 10;
  6. GridView1.PageSize = pageSize;
  7. populate(pageSize);
  8. }
  9. }

Step-13: Run Application.

No comments:

Post a Comment

How to register multiple implementations of the same interface in Asp.Net Core?

 Problem: I have services that are derived from the same interface. public interface IService { } public class ServiceA : IService { ...