Bootstrap Pagination for ASP.NET GridView
DEMO DOWNLOAD Bootstrap offers a pagination component that looks simple yet the large block is hard to miss, easily scalable, a...

https://www.programming-free.com/2013/07/bootstrap-pagination-for-aspnet-gridview.html
Bootstrap offers a pagination component that looks simple yet the large block is hard to miss, easily scalable, and provides large click areas. This is a static component and there are few dynamic jQuery plugins available that simplifies the rendering of Bootstrap Pagination. In this post, I am going to use BootPag jQuery plugin and implement server side paging in ASP.Net GridView.
jQuery Bootpag is an enhanced bootstrap pagination plugin. It is very easy to set up – we only have to pass a callback function and listen for the page event. Inside that function, we can update the GridView with the content by making ajax calls to server side web method.
1. Create an ASP.NET Web Application. Download and required scripts to it,
2. Let us use a csv file with some sample data to populate gridview. I have created a csv file and stored it in Project/App_Data folder.
We need a model class to represent the columns in the csv file (country, revenue, salemanager, year). I am implementing server side pagination in this example and at any point of time I am returning only 5 records (maximum records per page) from the server.
We need a model class to represent the columns in the csv file (country, revenue, salemanager, year). I am implementing server side pagination in this example and at any point of time I am returning only 5 records (maximum records per page) from the server.
Revenue.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; using System.Web; namespace GridViewBootstrapPagination { public class Revenue { public Revenue(string country, string revenue, string salesmanager, string year) { this.country = country; this.revenue = revenue; this.salesmanager = salesmanager; this.year = year; } public Revenue() { } public string country { get; set; } public string revenue { get; set; } public string salesmanager { get; set; } public string year { get; set; } public List<Revenue> GetRevenueDetails(int pagenumber,int maxrecords) { List<Revenue> lstRevenue = new List<Revenue>(); string filename = HttpContext.Current.Server.MapPath("~/App_Data/country_revenue.csv"); int startrecord = (pagenumber * maxrecords) - maxrecords; if (File.Exists(filename)) { IEnumerable<int> range = Enumerable.Range(startrecord, maxrecords); IEnumerable<String> lines = getFileLines(filename, range); foreach (String line in lines) { string[] row = line.Split(','); lstRevenue.Add(new Revenue(row[0], row[1], row[2], row[3])); } } return lstRevenue; } public static IEnumerable<String> getFileLines(String path, IEnumerable<int> lineIndices) { return File.ReadLines(path).Where((l, i) => lineIndices.Contains(i)); } public int GetTotalRecordCount() { string filename = HttpContext.Current.Server.MapPath("~/App_Data/country_revenue.csv"); int count = 0; if (File.Exists(filename)) { string[] data = File.ReadAllLines(filename); count= data.Length; } return count; } } }
4. Next let us create a web form with a gridview, and use bootpag plugin to generate pagination component for the gridview,
Default.aspx
<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title>Bootstrap Pagination for GridView</title> <link href="Styles/bootstrap.min.css" rel="stylesheet" /> <script src="Scripts/jquery-1.8.2.js"></script> <script src="Scripts/jquery.bootpag.min.js"></script> <script type="text/javascript"> $(document).ready(function () { // init bootpag var count = GetTotalPageCount(); $('#page-selection').bootpag( { total:count }).on("page", function (event, num) { GetGridData(num); }); }); function GetGridData(num) { $.ajax({ type: "POST", url: "Default.aspx/GetRevenueDetail", data: "{ \"pagenumber\":" + num + "}", contentType: "application/json; charset=utf-8", dataType: "json", success: function (data) { bindGrid(data.d); }, error: function (xhr, status, err) { var err = eval("(" + xhr.responseText + ")"); alert(err.Message); } }); } function bindGrid(data) { $("[id*=gvBSPagination] tr").not(":first").not(":last").remove(); var table1 = $('[id*=gvBSPagination]'); var firstRow = "$('[id*=gvBSPagination] tr:first-child')"; for (var i = 0; i < data.length; i++) { var rowNew = $("<tr><td></td><td></td><td></td><td></td></tr>"); rowNew.children().eq(0).text(data[i].country); rowNew.children().eq(1).text(data[i].revenue); rowNew.children().eq(2).text(data[i].salesmanager); rowNew.children().eq(3).text(data[i].year); rowNew.insertBefore($("[id*=gvBSPagination] tr:last-child")); } } function GetTotalPageCount() { var mytempvar = 0; $.ajax({ type: "POST", url: "Default.aspx/GetTotalPageCount", data: "", contentType: "application/json; charset=utf-8", dataType: "json", async:false, success: function (data) { mytempvar=data.d; }, error: function (xhr, status, err) { var err = eval("(" + xhr.responseText + ")"); alert(err.Message); } }); return mytempvar; } </script> </head> <body> <form id="form1" runat="server"> <div style="width:670px;margin-left:auto;margin-right:auto;"> <asp:GridView ID="gvBSPagination" runat="server" CssClass="table table-striped table-bordered table-condensed" Width="660px" AllowPaging="true" PageSize="5" OnPreRender="gvBSPagination_PreRender"> <PagerTemplate> <div id="page-selection" class="pagination-centered"></div> </PagerTemplate> </asp:GridView> </div> </form> </body> </html>
Now let us take a closer look at the jQuery script. Initially when the page loads, an ajax call will be made to server side method called, GetTotalPageCount - this method fetches the total number of records contained in the csv file once when the page initially loads. This is required because we have to pass total record count as input for bootpag plugin to generate list of paging controls based on it(option : total). GridView is loaded with the first five records on page load from the server side and on every click on the pager control, ajax call is made to the server side method called, GetGridData with the current page number as parameter - this method is responsible for fetching records from csv file based on the current page number.
Note that GridView has a pager template in which a div with id "page-selection" is placed. Bootpag plugin generates list of paging controls inside this div on page load.
5. Final step is to load gridview on Page_Load and define server side Web Method to execute jQuery Ajax Calls in the code behind file,
Default.aspx.cs
using System; using System.Collections.Generic; using System.Data; using System.IO; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.Services; using System.Web.Script.Services; namespace GridViewBootstrapPagination { public partial class Default : System.Web.UI.Page { private const int MAX_RECORDS = 5; protected void Page_Load(object sender, EventArgs e) { string filename = Server.MapPath("~/App_Data/country_revenue.csv"); if (!IsPostBack) { List<Revenue> revenue = GetRevenueDetail(1); gvBSPagination.DataSource = revenue; gvBSPagination.DataBind(); } } [WebMethod] [ScriptMethod(UseHttpGet = false, ResponseFormat = ResponseFormat.Json)] public static List<Revenue> GetRevenueDetail(int pagenumber) { Revenue rv = new Revenue(); List<Revenue> lstrevenue = rv.GetRevenueDetails(pagenumber,MAX_RECORDS); return lstrevenue; } [WebMethod] [ScriptMethod(UseHttpGet = false, ResponseFormat = ResponseFormat.Json)] public static int GetTotalPageCount() { int count=0; Revenue rv=new Revenue(); count = rv.GetTotalRecordCount(); count = count / MAX_RECORDS; return count; } protected void gvBSPagination_PreRender(object sender, EventArgs e) { GridView gv = (GridView)sender; GridViewRow pagerRow = (GridViewRow)gv.BottomPagerRow; if (pagerRow != null && pagerRow.Visible == false) pagerRow.Visible = true; } } }
That is all! Now run the project and view "Default.aspx" in browser to see the gridview working with Bootstrap Pagination component.
Update: There is one more easy way of doing this. bs.pagination.js is a jquery script written by Issam Ali and is way more simpler than the approach i explained above. Please have a look at the below links,
https://github.com/issamalidev/bs.pagination.js
http://stackoverflow.com/questions/22420602/simple-script-to-apply-bootstrap-pagination-style-in-asp-net-gridview
Please leave your comments and queries about this post in the comment sections in order for me to improve my writing skills and to showcase more useful posts.Thanks for reading!!
how its work when there is 6 data and i want to show 4 per page??
ReplyDeleteHi. Great Tutorial. I have tried to implement it with my own csv file, but my problem is as follows:
ReplyDeleteI just addded a extra coulomb, but it doesnt show it on gridview? Is there somewhere I forgot to change?
Nevermind, found it :) Great tutorial though!
DeleteHow would I use a SQL datasource with this? What about your example would be different?
ReplyDeletethanks for great tutorial
ReplyDeletegood article but can not validate any control on page as Webmethod static method not allowing to access any control of page.
ReplyDeletehow to use sql server data with your examlpe.. code plz..
ReplyDeletemail id rahul.sharma@programmer.net
Thanks for this innovative blog. Keep posting the updates.
ReplyDeletepearson vue
German Language Classes in Chennai
IELTS Training in Chennai
Japanese Language Course in Chennai
spanish classes in chennai
Best Spoken English Classes in Chennai
Spoken English Classes in Velachery
Spoken English Classes in Tambaram
Thanks to the author for sharing this great valuable post with us.
ReplyDeleteIELTS Classes in Mumbai
IELTS Coaching in Mumbai
IELTS Mumbai
IELTS Center in Mumbai
Best IELTS Coaching in Mumbai
Spoken English Classes in Chennai
Spoken English Class in Chennai
Spoken English in Chennai
Thanks for the author for such a valuable post..
ReplyDeleteSAP Training in Chennai
Pearson Vue Exam Center in Chennai
Great Article. Thank you for sharing! Really an awesome post for every one.
ReplyDeleteIEEE Final Year projects Project Centers in Chennai are consistently sought after. Final Year Students Projects take a shot at them to improve their aptitudes, while specialists like the enjoyment in interfering with innovation. For experts, it's an alternate ball game through and through. Smaller than expected IEEE Final Year project centers ground for all fragments of CSE & IT engineers hoping to assemble. Final Year Project Domains for IT It gives you tips and rules that is progressively critical to consider while choosing any final year project point.
Spring Framework has already made serious inroads as an integrated technology stack for building user-facing applications. Spring Framework Corporate TRaining the authors explore the idea of using Java in Big Data platforms.
Specifically, Spring Framework provides various tasks are geared around preparing data for further analysis and visualization. Spring Training in Chennai
Excellent blog, this blog gives more useful information, waiting for more updates
ReplyDeleteDevOps Training in Chennai
DevOps Training in Bangalore
Best DevOps Training in Bangalore
DevOps Course in Bangalore
DevOps Training Bangalore
DevOps Training Institutes in Bangalore
DevOps Training in Marathahalli
AWS Training in Bangalore
Data Science Courses in Bangalore
PHP Training in Bangalore
Clipping Xpert
ReplyDeleteClipping Xpert India
Paragon Clipping Path
Clipping Path Service
Image Editing Company
Ecommerce Image Editing Service
Clipping path company
Clipping Path Service
Image Editing Company
Ecommerce Image Editing Service
Clipping path company
Clipping Path Service
Image Editing Company
Ecommerce Image Editing Service
Clipping path company
Amazing Article, Really useful information to all So, I hope you will share more information to be check and share here.
ReplyDeleteflask in python
how to install flask in python
what is flask in python
flask in python tutorial
how to create a web page using flask in python
rest api using flask in python
how to install flask in python without pip
flask in python is used for
what is flask in python used for
learn flask in python
Social media marketing is one of the very effective methods in digital marketing strategies. The social media marketing tools are involved with various social media sites. data science course syllabus
ReplyDeleteGreat Article. Thank you for sharing! Really an awesome post for every one.
ReplyDeleteđại lý vé máy bay đi nhật
giá vé máy bay đi hàn quốc của vietjet
vé máy bay eva đi đài loan>
giá vé máy bay đi bắc kinh trung quốc
Truly, this article is really one of the very best in the history of articles. I am a antique ’Article’ collector and I sometimes read some new articles if I find them interesting. And I found this one pretty fascinating and it should go into my collection. Very good work!
ReplyDeletedata science course in India
Really nice and interesting post. I was looking for this kind of information and enjoyed reading this one. Keep posting. Thanks for sharing.
ReplyDeleteArtificial Intelligence Course
This is great. Brother Printer Drivers. Thank you so much.
ReplyDeleteThanks for sharing such a great blog......!!!
ReplyDeletefull form
full form of nrc
nrc full form
mbbs full form
full form of rip
The blog written is extremely impressive, with a great topic. However, a bit more research could have strengthened it even further. You can explore the services as offered by livewebtutors a premium academic writing services platform offering the best of MLA Referencing Generator teamed with knowledge and experience.
ReplyDeleteMua vé máy bay liên hệ Aivivu, tham khảo
ReplyDeletevé máy bay đi Mỹ giá rẻ 2021
vé máy bay từ mỹ về việt nam mùa dịch
mở chuyến bay từ nhật về việt nam
các đường bay từ canada về việt nam
ReplyDeleteI always appreciated your work, your creation is definitely unique. Great job
rasmussen student portal
Superb post however , I was wanting to know if you could write a little more on this subject? I’d be very grateful if you could elaborate a little bit further. Cheers! 토토
ReplyDeleteThe site loading speed is incredible. It seems that you’re doing any distinctive trick. Furthermore, The contents are masterpiece. you’ve done a magnificent activity on this topic!
ReplyDelete온라인카지노사이트
안전놀이터
토토
I like the efforts you have put in this, appreciate it for all the great content.
ReplyDelete사설토토
바카라사이트
파워볼사이트
I like what you guys are up also. Such clever work and reporting! Keep up the excellent works guys I’ve incorporated you guys to my blogroll. I think it’ll improve the value of my web site
ReplyDelete토토사이트
스포츠토토
That's a great article! The neatly organized content is good to see. Can I quote a blog and write it on my blog? My blog has a variety of communities including these articles. Would you like to visit me later? 온라인홀덤
ReplyDeleteHello, I'm happy to see some great articles on your site. Would you like to come to my site later? My site also has posts, comments and communities similar to yours. Please visit and take a look 사설토토사이트
ReplyDeleteSimply unadulterated brilliance from you here. I have never expected something not as much as this from you and 먹튀검증 have not confounded me by any reach out of the inventive vitality. I acknowledge you will keep the quality work going on.
ReplyDeleteI am overwhelmed by your post with such a nice topic. Usually I visit your 안전놀이터 and get updated through the information you include but today’s blog would be the most appreciable. Well done! What an interesting story! I'm glad I finally found what I was looking for 메이저토토사이트. I think a lot of articles related to 메이저사이트 are disappearing someday. That's why it's very hard to find, but I'm very fortunate to read your writing. When you come to my site, I have collected articles related to this. My site name is . This is a great post!I didn't overdo it because of the inflated content , and I feel that I tried to keep the reader from 토토사이트 feeling the burden with concise content.
ReplyDeleteIt seems to be a really interesting article. After reading this article, I thought it was interesting, so I wrote it. I hope you can come to my site, 주식디비, read it and enjoy it.
ReplyDeleteThanks for sharing such nice info. I hope you will share more information like this. please keep on sharing!
ReplyDeletePython Training In Bangalore | Python Online Training
Artificial Intelligence Training In Bangalore | Artificial Intelligence Online Training
Data Science Training In Bangalore | Data Science Online Training
Machine Learning Training In Bangalore | Machine Learning Online Training
AWS Training In Bangalore | AWS Online Training
IoT Training In Bangalore | IoT Online Training
Adobe Experience Manager (AEM) Training In Bangalore | Adobe Experience Manager (AEM) Online Training
Oracle Apex Training In Bangalore | Oracle Apex Online Training