Introduction
I searched the entire web looking for tutorials about custom paging in GridView control in ASP.Net 2.0. Since GridView is relatively new to ASP.Net, most of my search returned custom paging using DataGrid Control.
To help others who have the same problem as I encountered today, here is the tutorial regarding custom paging in GridView. I hope you’ll have a great time reading my article as I have writing it.
Derek Klingman said
Man you are a life saver!!! This was exactly what I was looking for. Thanks sooo much!!!
Chad Boulton said
Hey, why are my pager buttons in the first column of the gridView? Why does it only create one cell? I’d love to do a colspan, but gridview.BottomPagerRow is always null!? — any ideas?…
grminds said
A nice article.This helped me a lot while implementing custompaging.
Edison said
Nice and cool article,
you make me to be a looser!
maggie said
it is just what i want to do these days! cool….
maggie said
I use objectDataSource to bind gridview control,
can i just use:
// popultate the gridview control
eGridView.databind()
but,the paging doesn’t work, any idea?
John said
I don’t understand which event that procedure “protected void Paginate(object sender, CommandEventArgs e)” hand for ? and What does “PopulateGrid()” do ?;
chakrit said
just what I’m looking for! thanks for taking the time to explain this out
Tim said
Hi. Very nice. Is there a way I can switch the image to a disabled one (first and previous) when I am on page one? Thanks.
Tim said
When does
Protected Sub Paginate(ByVal sender As Object, ByVal e As System.EventArgs)
get called?
Tim said
Hi, instead of a DropDown to select a page can a numeric pager be displayed along with the buttons in the PagerTemplate?
Hzaleoanodon said
Really Really good article. Cheers :)
Dony said
A really cool article, help me a lot….
Thanks
Vince said
Hi,
i’m newbie to asp.net, I ran few test on your code and it give me several errors.
First, “grdlistings”, “grdInvestors”, and “populateGrid” does not exist in the current context.
Am i missing something in the program?
Any help would be appreciate.
Thanks
Doyle said
wat about if i want the format is like this
|> >|
Doyle said
1> >1
Doyle said
<
Doyle said
|< << 1234 >> <|
Brian Wallace said
How do I get the drop downlist to work correctly. I cannot get it to fire the SelectedIndexChanged even when I select a new item. This seems to be becuase when the page loads, there isn’t anything in the list until I dynamically create the list… If anyone has it working, I sure would like to know more about how to get that piece to work, the rest works fine.
BTW Doyle, I was creating the a post on my blog that addressed your question when I discovered this blog, you can check out the post at: http://aspadvice.com/blogs/net_discoveries/default.aspx
Kostis M said
A really good article, help me a lot….
but, if we have a large number of pages (i.e. 100 or more),
the dropdown list I thing is not very easy to accomodate.
I should like to see an alternate method with (say) a textbox
or something similar.
Thanks a lot
yaron said
I’m trying to use it with an update panel. How do I reference the dropdownlist control in the Triggers section?
Thanks,
Yaron.
charles said
where is the F### vB?
and where are the individual images for the example? a fake picture of the control sucks
Aizal said
Thank you for the really really great article!!
Julio Szabo said
Thanks, this is wonderful, whith any modification, it’s work good and it’s that I was looking for.
Thanks again.
Minhtv said
Can you help me?
I’m using asp.net 1.0, i don’t have tool as athlast to support ajax. If you have , can you give me it?
thank you!
Balamurugan.M said
Hai!
Very good explanation of each and everything about paging in GridViewControl.This will be very helpful and useful to evry programmers.
Ryan said
Thank you writing this, it helped a lot! I wanted to mention, I’m sure most people already know this, the key words for the paging, first, prev, nex, and last are very specific and if you deviate from them it messes it up. For example, you can’t use previous as the argument . . .
Thanks again!
Ryan
Mycole said
This article was helpful, but I found that after following the directions outlined here, I couldn’t get the PagerTemplate to show up. I was trying to use Custom Paging and only was retrieving exactly the rows needed to be displayed.
I discovered that I needed to add the following:
gvrPager.Visible = true;
protected void grdListings_DataBound(Object sender, EventArgs e)
{
GridViewRow gvrPager = grdListings.BottomPagerRow;
if (gvrPager == null)
return;
gvrPager.Visible = true;
//…..
}
Hopefully, I’ll save someone else a few hours.
Mycole
partha said
hi,
your code helped me a lot and i have problem can we disable those pagertemplete buttons.
regards,
Parth
Ramon Rocha said
Dear sir,
I was converted the code for VB
I have a problem: whenever I have, for instance, 4 lines in a page that possesses up to 5 of total, when I click in the nexr button, the pagination control disappears together with the last line of the gridview…
Página
de
Protected Sub grdTabela_SelectedIndexChanged(ByVal sender As Object, ByVal e As EventArgs) Handles grdTabela.SelectedIndexChanged
Dim gvrPager As GridViewRow = grdTabela.BottomPagerRow
Dim cboPages As DropDownList = CType(gvrPager.Cells(0).FindControl(“cboPages”), DropDownList)
grdTabela.PageIndex = cboPages.SelectedIndex
grdTabela.DataBind()
End Sub
Protected Sub Paginate(ByVal sender As Object, ByVal e As CommandEventArgs)
Dim intCurIndex As Integer = grdTabela.PageIndex
Select Case e.CommandArgument.ToString.ToUpper
Case “FIRST”
grdTabela.PageIndex = 0
Case “PREV”
intCurIndex = intCurIndex – 1
grdTabela.PageIndex = intCurIndex
Case “NEXT”
intCurIndex = intCurIndex + 1
grdTabela.PageIndex = intCurIndex
Case “LAST”
grdTabela.PageIndex = grdTabela.PageCount
End Select
grdTabela.DataBind()
End Sub
Protected Sub cboPages_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs)
Dim gvrPager As GridViewRow = grdTabela.BottomPagerRow
Dim cboPages As DropDownList = CType(gvrPager.Cells(0).FindControl(“cboPages”), DropDownList)
grdTabela.PageIndex = cboPages.SelectedIndex
End Sub
Ramon Rocha said
I’m sorry by my poor english (from Brazil)
Someone said
Just so everyone knows, the sub “Paginate” doesn’t work. Go to
http://blog.wekeroad.com/archive/2006/12/09/GridView-Sorting-And-Paging–My-Pain-Your-Gain.aspx
for a complete description of a functional paging using the above concept.
Rishi said
It’s really a nice article and helps to reduce many lines of code when I was using Repeater control and enabling paging to it.
I have used this article with NextPrevious option and it works fine. Now I want to have this option on top and bottom both place of the gridview. How I can achieve this? please help
Thanks.
Rob said
Great article! Helped me out a lot.
One mistake I saw:
grdListings.PageIndex = grdListings.PageCount;
should be
grdListings.PageIndex = grdListings.PageCount – 1;
the GridView probably handles it gracefully, but PageCount is zero-based.
Joshua said
I’m having the same problem as below. I replaced the grdListings and grdInvestors with my own gridview name but what is populateGrid()? It’s not working for me.
Please advise!
“Hi,
i’m newbie to asp.net, I ran few test on your code and it give me several errors.
First, “grdlistings”, “grdInvestors”, and “populateGrid” does not exist in the current context.
Am i missing something in the program?
Any help would be appreciate.
Thanks
“
Smita said
Cool !!!!
but i wanted alphabetic paging ?
can that be achieved too???
docxy said
Very Nice. Took some modification but I finally got it top work in VB.NET.
Thanks.
victoria said
Very useful code .
Thankyou Very Much
Abhishek said
Hi,
This was a very helpful article for me.
And it helped me a lot in my function.
Really thanks a lot . this was very descriptive and easy to understand.
John said
Nice work thanks… If you are planning to use the code you might need to do some minor modifications and it should work.
George Zhu said
Very good one, which helps me a lot.
Matt said
Awsome job! You are a lifesaver!
Shobha said
Its nice
Deepti said
Thank you!!!!
Thankyou!!!
Buddy great job!!!
Have a great day!!!
Airstrike said
Where do you live? I want to come give you a kiss!
DanR said
I’ve been trying to paging for awhile. Starting from my MasterPage/AJAX/nStuff/CSS Friendly I got no where, but I start with your sample, and add just CSS Friendly support for GridView, paging disappears totally. Not using CSS Friendly, just copying in the adapters.
Any suggestions would be helpful.
Zewaccert said
Follow these guidelines and you will build that new home with little, or no, problems. replacement window minnesota can help…
naisioxerloro said
Hi.
Good design, who make it?
Duy Tan said
what i have to do if i want to put numeric pages behind combobox?
thanks a lot!
Yasser said
Thank you very much it is a great article
But i can add code :
In Event protected void GridView1_DataBound(object sender, EventArgs e)
we can add this code
//– For First and Previous ImageButton
if (GridView1.PageIndex == 0)
{
//((ImageButton)GridView1.BottomPagerRow.FindControl(“btnFirst”)).Enabled = false;
//((ImageButton)GridView1.BottomPagerRow.FindControl(“btnFirst”)).Visible = false;
//((ImageButton)GridView1.BottomPagerRow.FindControl(“btnPrev”)).Enabled = false;
//((ImageButton)GridView1.BottomPagerRow.FindControl(“btnPrev”)).Visible = false;
//— OR —\\
ImageButton btnFirst = (ImageButton)row.Cells[0].FindControl(“btnFirst”);
ImageButton btnPrev = (ImageButton)row.Cells[0].FindControl(“btnPrev”);
btnFirst.Visible = false;
btnPrev.Visible = false;
}
//– For Last and Next ImageButton
if (GridView1.PageIndex+1 == GridView1.PageCount)
{
//((ImageButton)GridView1.BottomPagerRow.FindControl(“btnLast”)).Enabled = false;
//((ImageButton)GridView1.BottomPagerRow.FindControl(“btnLast”)).Visible = false;
//((ImageButton)GridView1.BottomPagerRow.FindControl(“btnNext”)).Enabled = false;
//((ImageButton)GridView1.BottomPagerRow.FindControl(“btnNext”)).Visible = false;
//— OR —\\
ImageButton btnLast = (ImageButton)row.Cells[0].FindControl(“btnLast”);
ImageButton btnNext = (ImageButton)row.Cells[0].FindControl(“btnNext”);
btnLast.Visible = false;
btnNext.Visible = false;
}
Regards,
Yasser Zaid
AjAs said
Thanks
We had used your code and it is working well . Before trying this we had used following code it is also nice one Please check
<asp:SqlDataSource ID=”SqlDataSource1″ runat=”server” SelectCommand=”SELECT [au_id], [au_lname], [au_fname], [phone], [address], [city], [state], [zip], [contract] FROM [authors]”
ConnectionString=”" />
Thanks and Regards
Ashish and Ajay
Manoj Paul said
great article…… I really like your way of explaination.
Adrian said
Great article. But why Paginate rutine is executed ?
It even work even the name Paginate is changed with something else, like Abc for example.
So (per VB Example)
Protected Sub Abc(ByVal sender As Object, ByVal e As System.EventArgs)
Dim CurrentIndex As Integer = GridView1.PageIndex
Dim StrVal As String = e.ToString.ToLower
Select Case StrVal
Case “first”
CurrentIndex = 0
Case “prev”
CurrentIndex = CurrentIndex – 1
Case “next”
CurrentIndex = CurrentIndex + 1
Case “last”
CurrentIndex = GridView1.PageCount
End Select
works too !!!
thx
Bhavesh said
hello,
I can not get it to fire selectedindexchanged event for the ddlpages dropdownlist box becuase that control is included in Pager Template portion of the Gridview.
Can anybody guide me in this matter?
Thanks,
B
Iqbal Mahar said
For Bhavesh
U simply go to ur edit templet for pager and doubble clik the dropdown u will be able to get the required event
Gren said
Actually, I had a similar problem getting the SelectedIndexChanged event to fire because of the way I am binding to the datasource. I wired it up correctly, it just wasn’t recognizing my input. So, instead, I used the OnUnload event.
Gren said
BTW… I also got it to work with the SelectedIndexChanged event. However, to do so I had to attach the GridView to an ObjectDataSource (I assume a SQLDataSource would have also worked).
Previously, I was filling it with an external class. I believe this threw off the order in which the events were being fired, so the SelectedIndexChanged event was never actually occurring.
Jeremy said
The VB code is actually fairly straight foward. A couple of comments:
1) I don’t know if I missed it from translating the orginal C# code, but I didn’t see where the “Paginate” routine updated the content of the dllPages control to show the current page. I added that to my code below.
2) As noted in one of the comments above the default handler for the dllPages_SelectedtIndexChanged is created when you double-click the drop down control in the pager template for the grid control.
3) If you want the page control in the top position of the gridview you will need to use the TopPageRow collection.
4) If you want to have the pager in both the top and the bottom positions. How do you determine which of the ddlPages drop downs was selected? When both positions are active there are 2 instantiations of the ddlPages control. From some quick experiements I noted that the 2 controls do not automatically synchronize values.
Anyway here in the VB code:
Protected Sub GridView1_DataBound(ByVal sender As Object, ByVal e As System.EventArgs) Handles GridView1.DataBound
‘ Define variables
Dim ddl As DropDownList
Dim lbl As Label
‘ Make certain there are pages/rows to display
If (GridView1.PageCount > 0) Then
‘ Get the controls from the gridview for the botton pager row
ddl = GridView1.BottomPagerRow.Cells(0).FindControl(“ddlPages”)
lbl = GridView1.BottomPagerRow.Cells(0).FindControl(“lblPageCount”)
‘ Clear and populate the ddl control
ddl.Items.Clear()
For counter = 1 To GridView1.PageCount
ddl.Items.Add(counter.ToString)
If (GridView1.PageIndex = counter – 1) Then
ddl.SelectedItem.Value = counter – 1
ddl.SelectedValue = counter
End If
Next
‘ Set the total pages content
lbl.Text = GridView1.PageCount.ToString
End If
End Sub
Protected Sub Paginate(ByVal sender As Object, ByVal e As System.EventArgs)
‘ Get the current page selected
Dim intCurIndex As Integer
Dim ddl As DropDownList
‘ Get the current index
intCurIndex = GridView1.PageIndex
‘ Reset the page
Select Case (e.ToString.ToLower)
Case “first” : GridView1.PageIndex = 0
Case “prev” : GridView1.PageIndex = intCurIndex – 1
Case “next” : GridView1.PageIndex = intCurIndex – 1
Case “last” : GridView1.PageIndex = GridView1.PageCount
End Select
‘ Reset the drop down value
ddl = GridView1.BottomPagerRow.Cells(0).FindControl(“ddlPages”)
ddl.SelectedValue = GridView1.PageIndex + 1
End Sub
Protected Sub ddlPages_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs)
‘ Define variqbles
Dim ddl As DropDownList
‘ Get the contents of the drop down and set it into the page index
ddl = GridView1.BottomPagerRow.Cells(0).FindControl(“ddlPages”)
GridView1.PageIndex = ddl.SelectedIndex
‘ Execute the current search
ExecuteSearch()
End Sub
Janarthanan said
Thanks.. Good Code, It works fine…
Mukesh said
Really a Gud atrtical , i appriciate ur work !!!
to make Pageinate works.
you have to add Oncommand in ur Image buttons
like i have added below
…
…
Mukesh said
OnCommand=”Paginate”
Suresh.S said
Plz.. Help to me.. Acuallly This al the codes are working very well but the problem is, When i press the Previous button,the prolem is araise that is When the PageIndex reach 0,if we press the previous botton mean the error will araise and How to set true / false for enable and visible property for GridView Pagination image.Actuallly this code is not work.So plz help to me..
Balaji said
Execellent, only error is OnCommand=”Paginate”. But how to implement GridView1.SelectedIndexChanged event when we click on the pagination number 1 2 3 4 5 6 >> …. How will we get the value in the event method when user clicks some number below the gridview.
-Balaji k n
Krishna Chaitanya said
Hi,
u r c# code is excellent,
but instead of Dropdownlist i want numeric values like
First Previous 123456…… Next Last
like that i want can u please help me
Thank u!!!!
Felix said
Hi!
Very good code!
The paging works great with “first”, “prev”, “next” and “last” buttons and the dropdown change when I click on them.
But number 5: “OnSelectedIndexChanged on DropDownList to go to the selected page when a selection is made from our dropdown”
it’s never reached. =(
I select any page in dropdownlist, and after postback the selection in the gridview doesn’t change the page.
Why? Any idea?
Friday said
the PopulateGrid();method was not defined is that an omission or we are required to do that ourselves.
Thank you.
Anil said
When i select a page from dropdownlist(ddlpages) then it show blank page.
why?anyone help me?
Ajit Kumar said
Cutomized paging is not working properly.
Ajit Kumar said
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
LoadGridViewData();
}
}
protected void LoadGridViewData()
{
SqlConnection con = new SqlConnection(connectionString);
SqlDataAdapter da = new SqlDataAdapter();
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandText = “GetEmployeeDetails”;
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(“@PageIndex”, SqlDbType.Int).Value = GridView1.PageIndex + 1;
cmd.Parameters.Add(“@PageSize”, SqlDbType.Int).Value = GridView1.PageSize;
SqlParameter sqlParameter = cmd.Parameters.Add(“@totalRows”, SqlDbType.Int);
sqlParameter.Direction = ParameterDirection.Output;
da.SelectCommand = cmd;
DataTable dt = new DataTable();
da.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
if (cmd.Parameters["@totalRows"].Value != null)
{
totalRows = (Int32)cmd.Parameters["@totalRows"].Value;
}
int currentPageIndex = GridView1.PageIndex + 1;
lblCurrentPage.Text = currentPageIndex.ToString();
lblTotalPages.Text = CalculateTotalPages(totalRows).ToString();
}
private int CalculateTotalPages(int totalRows)
{
int result = totalRows / GridView1.PageSize;
int totalPages = result;
return totalPages;
}
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;
LoadGridViewData();
}
protected void Paginate(object sender, CommandEventArgs e)
{
switch (e.CommandName)
{
case “Previous”:
GridView1.PageIndex = GridView1.PageIndex – 1;
break;
case “Next”:
GridView1.PageSize = GridView1.PageIndex + 1;
break;
}
LoadGridViewData();
}
protected void GridView1_DataBound(object sender, EventArgs e)
{
if (GridView1.PageIndex == 0)
{
((Button)GridView1.BottomPagerRow.FindControl(“btnPrevious”)).Enabled = true;
((Button)GridView1.BottomPagerRow.FindControl(“btnNext”)).Enabled = true;
}
}
bhawana said
hi all,
plz tall me how we access value from gridview cell.
koy_chamnap said
Hey, tell me if you have any approach of this problem. I have been working with gridview with wizard of “Custom Paging in GridView Control”. It work better ,but I respectively wanna change from “paging linkbutton” that are at the “buttom of gridview control” to position in “gridview footer” ? ! . And I ask you whether or not it is possible to put “background image” for “pager of gridview control”. (Norton ,Cambodia)
Walter said
Using ASP.net and C# web page. I made a search that organizes Data grid, but I cant get it so if theres multiple pages of the same data that when i click to another link it sticks with the search criteria instead of reseting and going to page X of the WHOLE thing
Cool said
Well, guys,
any one know, how to get the total number of pages ie.e i wan to show
page: 3/9 in the gridview . i have the next previous buttons, but i also want to show the page number.
any one can share his thoughts.
sheers
Catherine said
Jeremy,
Thank you VERY much for the VB code.
James said
The link doesn’t work anymore
James said
Please update the link
evilripper said
LoL if I click “Read full…” the blog go in exception!! :-D
Fatal error: Call to undefined function wp() in /home/kikocom/public_html/wp-blog-header.php on line 13
mallikarjuna said
how to use paging in gridview control in c# and asp.net
Deepali said
Read full article link is not working.
ErTr said
click for cache of broken link..
http://209.85.229.132/search?q=cache:http://www.kiko-santos.com/2006/05/custom-paging-in-gridview-control/
Aaron said
Your link doesn’t work anymore…please update…
John Ace Smith said
Link not functional anymore
ErTr said
guys focus on sql paging.. its little hard to understand but you wil get the exactly what u want from the sql and dont need to struggle this listview, repeater bla bla craps.. its design is depends only you also.. search for sql rownumber u will love it..
shailesh said
hi friends,
can any one give the code of
custom gridview paging with
first prev 123456 next last
type of format, i have searched the entire site but not got any thing,this site link is not working,
friends please help me.
Thanks
shailesh said
hi friends,
can any one give the code of
custom gridview paging with
first prev 123456 next last
type of format, i have searched the entire site but not got any thing,this site link is not working,
friends please help me.
shailesh@seologistics.com
Thanks