web 2.0

Custom Paging in Grid view

So, it takes too long for me to write this post. even though I completed the coding stuff a week back but it is really hard to manage time these days.In this post, I will explain and demonstrate you how to create custom paging in Grid view control. Paging which works like the Google Paging. Let me elaborate more, say for example you have a record set of 500 items and you want to display 10 items per page. Now what happen to the pages numbers. Either you use the default with “..” sign after 10th page link which cause the post back and then get some new page numbers. Or you want to make it like Google. i.e as soon as user move forward on page index, hide the previous pages and show the new numbers and when user is getting back hide new numbers and show the previous page links. following image can give you some idea what we are going to do.gvpaging_scgvpaging_sc2To start, lets first create a Grid view .
   1: <asp:GridView ID="GridView1" runat="server" AllowPaging="True"
   2:     onrowcreated="GridView1_RowCreated" >
   3: </asp:GridView>
Yes, we have allow the paging but we are not going to use the default paging of asp.net. That is why we have write onrowcreated implementation in which we will simply detect and hide the pager row.
   1: protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e)
   2:  {
   3:      if (e.Row.RowType == DataControlRowType.Pager)
   4:      {
   5:          e.Row.Visible = false;
   6:      }
   7:  }
Now lets move to some global variables which we need through out our code.
   1: const int pageSize = 10;
   2: const int pageDispCount = 10;
   3: private DataTable dt = new DataTable();
pagesSize : number of records we want to display per page.pageDispCount : number of page numbers we want to display on custom paging.dt : A datatable which we will use to store data and use it on different post backs.Ok, now we need to get data from database, dump it to datatable and define the datasource of grid view.
   1: protected void bindData()
   2: {
   3:     SqlConnection objSqlCon = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["AdventureWorksConnectionString"].ToString());
   4:     objSqlCon.Open();
   5:
   6:     SqlDataAdapter objSqlDa = new SqlDataAdapter("select * from Production.Product", objSqlCon);
   7:
   8:     objSqlDa.Fill(dt);
   9:
  10:     GridView1.DataSource = dt;
  11:     GridView1.DataBind();
  12:
  13:     managePaging(dt);
  14: }
On line number 13, managePaging function will be used later to implement the paging logic. But before that, lets understand that we have taken the datatable as a global variable and each time after postback when we try to read our datatable we will get no results because there is no state management for this object.So lets override the LoadViewState and SaveViewState function of System.Web.UI.Page to save and restore the datatable by using viewstate.
   1: protected override object SaveViewState()
   2: {
   3:   object baseState = base.SaveViewState();
   4:   return new object[] { baseState, dt };
   5: }
   6: protected override void LoadViewState(object savedState)
   7: {
   8:   object[] myState = (object[])savedState;
   9:   if (myState[0] != null)
  10:       base.LoadViewState(myState[0]);
  11:
  12:   if (myState[1] != null)
  13:   {
  14:       dt = (DataTable) myState[1];
  15:       GridView1.DataSource = dt;
  16:       GridView1.DataBind();
  17:
  18:       managePaging(dt);
  19:   }
  20:
  21:   }
Well, SaveViewState function is simply putting the base.SaveViewState object and datatable in and object and returning it. A Simple Logic :)Where as, LoadViewState is retrieving and type casting the object exactly in the sequence it was save in the SaveViewState method.
   1: protected void managePaging(DataTable _dt)
   2: {
   3:     if (_dt.Rows.Count > 0)
   4:     {
   5:
   6:         // Variable declaration
   7:         int numberOfPages;
   8:         int numberOfRecords = dt.Rows.Count;
   9:         int currentPage = (GridView1.PageIndex);
  10:         StringBuilder strSummary = new StringBuilder();
  11:
  12:
  13:         // If number of records is more then the page size (specified in global variable)
  14:         // Just to check either gridview have enough records to implement paging
  15:         if (numberOfRecords > pageSize)
  16:         {
  17:             // Calculating the total number of pages
  18:             numberOfPages = (int)Math.Ceiling((double)numberOfRecords / (double)pageSize);
  19:         }
  20:         else
  21:         {
  22:             numberOfPages = 1;
  23:         }
  24:
  25:
  26:         // Creating a small summary for records.
  27:         strSummary.Append("Displaying <b>");
  28:
  29:         // Creating X f X Records
  30:         int floor = (currentPage * pageSize) + 1;
  31:         strSummary.Append(floor.ToString());
  32:         strSummary.Append("</b>-<b>");
  33:         int ceil = ((currentPage * pageSize) + pageSize);
  34:
  35:         //let say you have 26 records and you specified 10 page size, 
  36:         // On the third page it will return 30 instead of 25 as that is based on pageSize
  37:         // So this check will see if the ceil value is increasing the number of records. Consider numberOfRecords
  38:         if (ceil > numberOfRecords)
  39:         {
  40:             strSummary.Append(numberOfRecords.ToString());
  41:         }
  42:         else
  43:         {
  44:             strSummary.Append(ceil.ToString());
  45:         }
  46:
  47:         // Displaying Total number of records Creating X of X of About X records.
  48:         strSummary.Append("</b> of About <b>");
  49:         strSummary.Append(numberOfRecords.ToString());
  50:         strSummary.Append("</b>Records</br>");
  51:
  52:
  53:         litPagingSummary.Text =  strSummary.ToString();
  54:
  55:
  56:         //Variable declaration 
  57:         //these variables will used to calculate page number display
  58:         int pageShowLimitStart = 1;
  59:         int pageShowLimitEnd = 1;
  60:
  61:
  62:
  63:         // Just to check, either there is enough pages to implement page number display logic.
  64:         if (pageDispCount > numberOfPages)
  65:         {
  66:             pageShowLimitEnd = numberOfPages; // Setting the end limit to the number of pages. Means show all page numbers
  67:         }
  68:         else
  69:         {
  70:             if (currentPage > 4) // If page index is more then 4 then need to less the page numbers from start and show more on end.
  71:             {
  72:                 //Calculating end limit to show more page numbers
  73:                 pageShowLimitEnd = currentPage + (int)(Math.Floor((decimal)pageDispCount / 2));
  74:                 //Calculating Start limit to hide previous page numbers
  75:                 pageShowLimitStart = currentPage - (int)(Math.Floor((decimal)pageDispCount / 2));
  76:             }
  77:             else
  78:             {
  79:                 //Simply Displaying the 10 pages. no need to remove / add page numbers
  80:                 pageShowLimitEnd = pageDispCount;
  81:             }
  82:         }
  83:
  84:         // Since the pageDispCount can be changed and limit calculation can cause < 0 values 
  85:         // Simply, set the limit start value to 1 if it is less
  86:         if (pageShowLimitStart < 1)
  87:             pageShowLimitStart = 1;
  88:
  89:
  90:         //Dynamic creation of link buttons
  91:
  92:         // First Link button to display with paging
  93:         LinkButton objLbFirst = new LinkButton();
  94:         objLbFirst.Click += new EventHandler(objLb_Click);
  95:         objLbFirst.Text = "First";
  96:         objLbFirst.ID = "lb_FirstPage";
  97:         objLbFirst.CommandName = "pgChange";
  98:         objLbFirst.EnableViewState = true;
  99:         objLbFirst.CommandArgument = "1";
 100:
 101:         //Previous Link button to display with paging
 102:         LinkButton objLbPrevious = new LinkButton();
 103:         objLbPrevious.Click += new EventHandler(objLb_Click);
 104:         objLbPrevious.Text = "Previous";
 105:         objLbPrevious.ID = "lb_PreviousPage";
 106:         objLbPrevious.CommandName = "pgChange";
 107:         objLbPrevious.EnableViewState = true;
 108:         objLbPrevious.CommandArgument = currentPage.ToString();
 109:
 110:
 111:         //of course if the page is the 1st page, then there is no need of First or Previous
 112:         if (currentPage == 0)
 113:         {
 114:             objLbFirst.Enabled = false;
 115:             objLbPrevious.Enabled = false;
 116:         }
 117:         else
 118:         {
 119:             objLbFirst.Enabled = true;
 120:             objLbPrevious.Enabled = true;
 121:         }
 122:
 123:
 124:         //Adding control in a place holder
 125:         plcPaging.Controls.Add(objLbFirst);
 126:         plcPaging.Controls.Add(new LiteralControl("&nbsp; | &nbsp;")); // Just to give some space 
 127:         plcPaging.Controls.Add(objLbPrevious);
 128:         plcPaging.Controls.Add(new LiteralControl("&nbsp; | &nbsp;"));
 129:
 130:
 131:         // Creatig page numbers based on the start and end limit variables.
 132:         for (int i = pageShowLimitStart; i <= pageShowLimitEnd; i++)
 133:         {
 134:             if ((Page.FindControl("lb_" + i.ToString()) == null) && i <= numberOfPages)
 135:             {
 136:                 LinkButton objLb = new LinkButton();
 137:                 objLb.Click += new EventHandler(objLb_Click);
 138:                 objLb.Text = i.ToString();
 139:                 objLb.ID = "lb_" + i.ToString();
 140:                 objLb.CommandName = "pgChange";
 141:                 objLb.EnableViewState = true;
 142:                 objLb.CommandArgument = i.ToString();
 143:
 144:                 if ((currentPage + 1) == i)
 145:                 {
 146:                     objLb.Enabled = false;
 147:                 }
 148:
 149:
 150:                 plcPaging.Controls.Add(objLb);
 151:                 plcPaging.Controls.Add(new LiteralControl("&nbsp; | &nbsp;"));
 152:             }
 153:         }
 154:
 155:         // Last Link button to display with paging
 156:         LinkButton objLbLast = new LinkButton();
 157:         objLbLast.Click += new EventHandler(objLb_Click);
 158:         objLbLast.Text = "Last";
 159:         objLbLast.ID = "lb_LastPage";
 160:         objLbLast.CommandName = "pgChange";
 161:         objLbLast.EnableViewState = true;
 162:         objLbLast.CommandArgument = numberOfPages.ToString();
 163:
 164:         // Next Link button to display with paging
 165:         LinkButton objLbNext = new LinkButton();
 166:         objLbNext.Click += new EventHandler(objLb_Click);
 167:         objLbNext.Text = "Next";
 168:         objLbNext.ID = "lb_NextPage";
 169:         objLbNext.CommandName = "pgChange";
 170:         objLbNext.EnableViewState = true;
 171:         objLbNext.CommandArgument = (currentPage + 2).ToString();
 172:
 173:         //of course if the page is the last page, then there is no need of last or next
 174:         if ((currentPage + 1) == numberOfPages)
 175:         {
 176:             objLbLast.Enabled = false;
 177:             objLbNext.Enabled = false;
 178:         }
 179:         else
 180:         {
 181:             objLbLast.Enabled = true;
 182:             objLbNext.Enabled = true;
 183:         }
 184:
 185:
 186:         // Adding Control to the place holder
 187:         plcPaging.Controls.Add(objLbNext);
 188:         plcPaging.Controls.Add(new LiteralControl("&nbsp; | &nbsp;"));
 189:         plcPaging.Controls.Add(objLbLast);
 190:         plcPaging.Controls.Add(new LiteralControl("&nbsp; | &nbsp;"));
 191:     }
 192:
 193: }
Yes, the code is complex that is why I wrote proper comments which will let you understand the stuff easily.One last thing which is left, is the implementation of dynamically created link button onclick event.
   1: void objLb_Click(object sender, EventArgs e)
   2: {
   3:     plcPaging.Controls.Clear();
   4:     LinkButton objlb = (LinkButton)sender;
   5:     GridView1.PageIndex = (int.Parse(objlb.CommandArgument.ToString()) - 1);
   6:
   7:     managePaging(dt);
   8: }
There it is, we have now completed Custom Paging in Grid View. If you want to download the source code, here is the VS 2008 Solution.Modifications: I have been receiving emails regarding the issues of this post. Especially with the initial five page numbers. I have modified this post to fix the bug it had. Please feel free to point further issues. Also, the download links are also modified.

Comments

mani , on 3/30/2009 3:35:43 AM Said:

mani

hi I have implemented the same on vb.net but its not showing the exact result first it showing the  1o records if i click 2 page it shows the same record , but if  click the previous page its shows only first 5 records

aghausman United States, on 5/15/2009 1:17:17 AM Said:

aghausman

Ok, I have updated the code .. can you please check that now ..

Naksha India, on 5/16/2009 10:36:52 PM Said:

Naksha

ya..i will try..before that i want to know can i use this with dataset rather than datatable? what is the difference btwn using datatable and dataset? y we cant use this in on rowcreated event?

Agha Usman Islamic Republic of Pakistan, on 5/18/2009 8:26:35 PM Said:

Agha Usman

Answer 1: Well, Dataset can contain multiple datatables, where as datatable is obviously a child of dataset. If you ever notice, when we provide dataset as the data source for Gridview we write ds.table(0). This is because we are referencing the first table of dataset.

Answer 2: We cannot use it in rowcreated event, because rowcreated event fire whenever a row created. It means, if you have 100 rows the functions will run 100 times. but we want to run it only one time after gridview binding.

Cheers

khairi amer Malaysia, on 5/20/2009 12:06:43 PM Said:

khairi amer

i don understand c#, can you write in vb code?

im need ur help for my portal project..

Suman Kumar Giri India, on 5/27/2009 9:53:50 PM Said:

Suman Kumar Giri

Reall Nice !! Thanks a Lot

Suman Kumar Giri India, on 5/27/2009 9:54:38 PM Said:

Suman Kumar Giri

Really Nice !! Thanks a Lot

Shailesh thapa India, on 5/29/2009 10:03:30 PM Said:

Shailesh thapa

hi,
    thanks for your beautiful posts,i am looking shopping cart built in c#,many sites have shown the cart but with no source code or without explaination.Can u post a beautiful article regarding the shopping cart and it's functionalitry, from the scratch to end,we all who are searching for shopping cart will be much much thankful of you.  

Thanks in advance
brooni.123@gmail.com

rakesh United States, on 6/1/2009 9:37:28 PM Said:

rakesh

hi i have implemented the same code but although the page numbers are changing in footer but the but page data is not changing,please check it.

iulian Romania, on 6/6/2009 10:36:18 AM Said:

iulian

Hello,
Thanks for this useful post.
I have a little problem...this method works perfect if i have only one grid per page. But for example...i have two grids first is visible second hidden.
When i press details on the first grid the  first grid become hidden and the second visible.
Now..the paging for the first wors perfect, but for the second appears the paging correct but when i press a link button from it doesn't do anything...do you please have any idea?
best regards

Jignesh United States, on 6/13/2009 11:03:05 AM Said:

Jignesh

Hi,

first thanks for code.

I have download Code.Grid is display well.But when I click on page index link button also on next,last it showing me same record.So can you give me the solution for that.

Jignesh United States, on 6/13/2009 11:14:37 AM Said:

Jignesh

hi I have tried your code but everytime it showing me same data on page change.Can you please please help me about

Alex Singapore, on 6/15/2009 9:51:08 AM Said:

Alex

Hi, first of all, thanks for the sharing. I'm facing the same problem, seems like the paging is not working. Is the link with updated source code?

Canary United States, on 7/20/2009 10:38:18 AM Said:

Canary

Hi. Would you please send me a vb version code? Thanks

RRaveen Singapore, on 7/24/2009 6:50:01 PM Said:

RRaveen

Hi Guys, You can convert vb.net code from his code very easily using this tool www.developerfusion.com/.../. Just copy the code and paste then just click button to convert. you will get Vb.NET code.

Thank you

suresh India, on 7/26/2009 9:27:09 PM Said:

suresh

The implementation is very good but I am having the same problem, when I navigate through paging the data is not refreshing, can you check and send me the updated source code.


Thanks

prashant kauthekar India, on 8/1/2009 3:40:25 AM Said:

prashant kauthekar

I used your code for pagination..its work fine....
but there is one issue in that for me.
i also used a featute for changing page size programatically on one button click event. i also change respective value of global variable 'pageSize' in that event.
But when second time after clicking button 'managePaging()' function called and its takes pagesize which is decleared bydefault not changed value.
(because first managePaging() called and then button click event called).

           can u help me in this issue.
           If u have any solution please post it ..its urgent to me..

  

visa India, on 8/4/2009 12:39:05 PM Said:

visa

Really Nice.Thanks..Its very useful for me

Stress Reduction Holiday Gifts United States, on 9/4/2009 4:48:09 PM Said:

Stress Reduction Holiday Gifts

I am not much of a guy who thinks in so deeply about web design but I think your post had some valid points in it. Like designers are forced to design stuff within the limited code available and not go beyond it, their innovation is somewhat limited but still I think Web Design won't die! I agree that Amazon and other some big sites won't have a blog but now a days it's very important to have some sort of option available so people can quickly communicate their thoughts. I think Amazon if wants to shift it to that, they can get a customized CMS for themselves.

evidence eliminator review United States, on 9/5/2009 11:15:07 PM Said:

evidence eliminator review

Hey - nice blog, just looking around some blogs, seems a pretty nice platform you are using. I'm currently using Wordpress for a few of my sites but looking to change one of them over to a platform similar to yours as a trial run. Anything in particular you would recommend about it?

backlink checker United States, on 9/6/2009 1:48:27 AM Said:

backlink checker

Dude.. I am not much into reading, but somehow I got to read lots of articles on your blog. Its amazing how interesting it is for me to visit you very often.

char broil grills United States, on 9/8/2009 10:29:20 PM Said:

char broil grills

That is some inspirational stuff. Never knew that opinions could be this varied. Thanks for all the enthusiasm to offer such helpful information here.

Lyrics United States, on 9/12/2009 4:41:03 AM Said:

Lyrics

Hey - nice blog, just looking around some blogs, seems a pretty nice platform you are using. I'm currently using Wordpress for a few of my sites but looking to change one of them over to a platform similar to yours as a trial run. Anything in particular you would recommend about it?

Linda Mirano United States, on 9/14/2009 8:00:05 PM Said:

Linda Mirano

Keep 'em coming... you all do such a great job at such Concepts... can't tell you how much I, for one appreciate all you do!

campioni di Black Jack India, on 9/16/2009 6:35:30 AM Said:

campioni di Black Jack


  

I personally have embraced the new technologies and the CMS platforms, I think the new tools only make the web designs better. I am glad that new technologies are coming out in web design that make things easier, improved, and better looking for design.

Rocket Italian United States, on 9/16/2009 2:41:44 PM Said:

Rocket Italian

I was looking for crucial information on this subject. The information was important as I am about to launch my own portal. Thanks for providing a missing link in my business.

send flower malaysia United States, on 9/17/2009 11:11:21 PM Said:

send flower malaysia

I was wondering what is up with that weird gravatar??? I know 5am is early and I'm not looking my best at that hour, but I hope I don't look like this! I might however make that face if I'm asked to do 100 pushups. lol

make money on twitter United States, on 9/18/2009 9:43:32 PM Said:

make money on twitter

I would like to thank you for the efforts you have made in writing this article. I am hoping the same best work from you in the future as well. In fact your creative writing abilities has inspired me to start my own BlogEngine blog now. Really the blogging is spreading its wings rapidly. Your write up is a fine example of it.

Variable Annuities Pros and Cons United States, on 9/22/2009 11:17:50 AM Said:

Variable Annuities Pros and Cons

Nice feature. I will bookmark your site to check if you write more about in the future. I am quite interested in this topic. I just hope you could add more posts like this in future.

Aloe Propolis Creme United States, on 9/23/2009 3:41:08 AM Said:

Aloe Propolis Creme

Thank you for the sensible critique. Me & my neighbour were preparing to do some research about that. We got a good book on that matter from our local library and most books where not as influensive as your information. I am very glad to see such information which I was searching for a long time.This made very glad Smile

reverse phone lookup United States, on 9/25/2009 5:32:45 AM Said:

reverse phone lookup

Nice detail! And the proper comments really do help to explain it.

cocktail dresses United States, on 10/16/2009 7:05:34 PM Said:

cocktail dresses

I wanted to thank you for this great read!! I definitely enjoying every little bit of it and I have you bookmarked to check out new stuff you post.

Rider profile India, on 11/21/2009 12:55:12 PM Said:

Rider profile

I have never ever read an interesting article about grid view.Thanks a lot for sharing it.Keep posting this type of knowledgeable post.

mallika India, on 11/22/2009 12:16:31 PM Said:

mallika

nice article?how to download source code?

Add comment


(Will show your Gravatar icon)

  Country flag

biuquote
  • Comment
  • Preview
Loading