Click here to Skip to main content
Click here to Skip to main content

GridView Custom Paging with PageSize Change Dropdown

By , 5 May 2008
 

GridView Custom paging with PageSize change dropdown

Introduction

The GridView is a very powerful control and has all the features including paging/sorting etc. But while using GridView in your project, you have to assign the PageSize property of the GridView programmatically, which users then cannot change. Sometimes, users require the feature to change the page size so that they could view more/less records per page. With one of my projects, I was asked to develop such a control with custom paging. I am sharing this with you so that you don't have to rework for such a control.

Using the code

The complete code and assemblies are attached with this article. You can download the MrllControlLib.dll and add a reference to it in your project. Once you add the control to your page, you can assign various properties in order to control the attribute set in the context menu. The following are some of the properties exposed:

  • ShowMrllCustomPaging boolean
  • CustomPagerCssClass
  • DefaultSortExpression

Note that if you have assigned ShowMrllCustomPaging=true, then the control will load all drop downs for paging, sorting (if the SortExpression is assigned) and the number of pages dropdown, otherwise it will work as a normal GridView. Also, make sure to handle all events like PageIndexChanging and OnSorting. I have added another event, OnPageSizeChanged, which is fired when the page-size drop down is changed. This event uses the PageSizeChangeEventArgs delegate and emits a new page-size value. The following is the implementation of the PageSizeChange event:

protected void gv1_PageSizeChange(object sender, PageSizeChangeEventArgs e) 
{ 
    gv1.PageSize= e.NewPageSize; 
    gv1.PageIndex = 0; 
    BindGrid(); 
}

The rest of the events like OnSorting/PageIndexChanging are the same as for the GridView.

About the code

The custom gridview control inherits from the .NET GridView control, and the OnRowCreated method is overriden in order to change the paging style. When there is more than one page, the default pager template is loaded. I clear all the controls in the pager template and add my controls for paging/sorting/the number of records drop down.

protectedd override OnRowCreated(GridViewRowEventArgs e) 
{ 
    if (e.Row.RowType == DataControlRowType.Pager) 
    { 
          e.Row.Cells[0].Controls.Clear(); 
          //Code to Add various Dropdown 
          //Add control to Row 
          // oOutertab is table containg all dropdown and Lable 
          
          e.Row.Cells[0].Controls.Add(oOutertab); 
    }
}

Now, the problem is when there is only one page, the PagerTemplate will not be created, so how can I put the custom paging and sorting dropdown? The answer is add a row to the GridView at position zero (just above the header row). I have done this by adding a row when the header is created.

protected override void OnRowCreated(GridViewRowEventArgs e)
{ 
    if (e.Row.RowType == DataControlRowType.Header) 
    { 
        if (PageCount ==1) 
        { 
            GridViewRow PagerRow = base.CreateRow(-1, -1, 
               DataControlRowType.Pager, DataControlRowState.Normal); 
            //Add Your container of controls in this New row 
            PagerRow.Cells.Add(new TableCell()); 
            PagerRow.Cells[0].Controls.Add(oTab);  
            PagerRow.Cells[0].ColumnSpan = this.Columns.Count; 
 
            //Add the New row at Position 0 of GrdView 
            Table grid = (Table)this.Controls[0]; 
                                grid.Rows.AddAt(0, PagerRow); 
        } 
    } 
}

Now, there is another issue. Once you add a row at position zero, then it will have the style of the header-template, since we added this row while the header row was getting created. So, to apply the correct styling on the correct row, we need to assign CustomPagerCssClass to the pager template and HeaderStyleCssClass to the Header template (which is at position 1 now), or we can assign CSS on the RowCreated event before adding a new row at position zero.

GridViewRow PagerRow = base.CreateRow(-1, -1, 
    DataControlRowType.Pager, DataControlRowState.Normal); 
if (this.CustomPagerCssClass != string.Empty) 
      PagerRow.CssClass = this.CustomPagerCssClass; 
 
if (this.HeaderStyle.CssClass != string.Empty) 
      e.Row.CssClass = this.HeaderStyle.CssClass; 
//Now Add Pager Row at Position zero 
Table grid = (Table)this.Controls[0]; 
grid.Rows.AddAt(0, PagerRow);

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Saifi Hasan
India India
Member
I have done Master Degree in Computers and MCAD and working on Microsoft technologie since last 4 yrs. Currently working with TCS (India).

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
QuestionRelated to pagingmemberPranjali Deshbhratar1 Aug '12 - 2:25 
As its showing record numbers like "Showing 1-5 of 20" in some cases it shows 1-5 of 0 mostly after selected index changed.
 
Please let me know the solution for it as soon as possible.
QuestionOne Issue with this Control's PagingmemberBrijesh Shah21 Nov '11 - 1:07 
Hi Team,
This is really nice control but i found one issue. if you have 15 row and per page there is 10 record so, you will get 2 pages and in Dropdown of No. of Row you will get as usual 10, 20, .. 100 now suppose, you select 20. so, that single page you will get all 15 record, which is correct.
Now, at that time your paging control will get lost. you will get red line at the top (where top pager control is binding) and footer you will get nothing even though you have both pager binding.
 
Is there any solution for this ?
 
Secondly how would i enable Sorting dropdown ? currently i don't have sorting feature even enablesorting is true and it's event is also handled.
Generaldid you used stored procedure to fetch data or notmemberimranslager17 May '10 - 5:08 
did you used stored procedure to fetch data or not
GeneralThere was an error rendering the control. Object reference not to set an instance of an object.membermandian23 Nov '09 - 1:13 
Its Nice ..
 
functions are working fine..
 
But i am facing one problem while drag and drop the control in web form..
 
Error is :
There was an error rendering the control.
Object reference not to set an instance of an object.
 

 
What is the problem and where is the problem ?
 
manimaran s.r

GeneralGood article but it should have little improvemetsmemberfellippe31 Mar '09 - 0:47 
For example you can override OnDataBound event in order to allow pager to be displayed even if you will have only one page in your girdview.
In order to do this you can put this code:
 
if (YourGV.Rows.Count != 0)
YourGV.BottomPagerRow.Visible = true;
 
and you can add the drop down list and other stuff in the Pager and it won't be any need to add another row at the bottom of the GridView.
 
Cheers,
Felipe
Questioncan this be used in a form?membermark chester goking13 Nov '08 - 19:51 
this would be real neat. if only it could be used in forms that is.
this is only good for asp.net
 
the features are more than sufficient
GeneralVery NICE! Thank You!memberMember 31061888 Nov '08 - 3:04 
Very NICE! Thank You!
The BEST code so far...
...How did you manage to do it?
Is there temaplate to start from? MSDN?
 
Thank you!
Good luck with your bright future!
 
Rune
GeneralRe: Very NICE! Thank You!memberankitagarwalpa1 Sep '11 - 20:52 
how to show total number of product i have use this dll showing product always 1
GeneralGood workmemberTittle Joseph31 Jul '08 - 0:24 
Hi Saifi, are you from HCL? then you might be knowing me. Good to see your this submission. I was searching for Custom Paging and came across this. I'm liking it and using the approach in my application.
 
Thanks
 
- Tittle

GeneralRe: Good workmemberSaifi Hasan1 Aug '08 - 12:33 
Hi sir, yes sir im have worked under you..how can i forget you. I also have added you on orkut.
 
Nobody is perfect i'm Nobody

GeneralThere was an error rendering the control.memberMaclir30 Jul '08 - 9:04 
First, thank you for what appears to be a great control. I'm trying to use this on a web application, and I included the dll in the project references. I then add an instance of the control onto my web page (adding the item in the toolbox, then putting it on the page). In design view, where the control is placed the control doesn't appear, rather, there is a box with an error message "There was an error rendering the control. Object reference not set to an instance of an object."
 
Is there anything else I need to do? I notice that on the aspx page, the @Register directive has appeared just under my @page directive. Might the reason be that I am using master pages, and this page is a web content form?
 
Thanks,
Ken
Questioncan not run the demomemberMember 10419921 Jul '08 - 6:20 
Every time I try to run I got this message
<add assembly="System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
 
what is going on
AnswerRe: can not run the demomemberMember 10419921 Jul '08 - 9:29 
would you please let me know your answer
GeneralRe: can not run the demomemberSaifi Hasan24 Jul '08 - 13:05 
I think you dont have Ajax Extension installed at ur PC. However this code does not use ajax extension at all. Eigther u install ajax extension or remove any reference to system.web.extension from web.confog file will work
 
Nobody is perfect i'm Nobody

GeneralCannot find column DESCmemberwissam116 Jul '08 - 19:37 
Thank you for the useful article.
 
But when i run the TestApp then i get "Cannot find column DESC" error.
 
regards.
GeneralRe: Cannot find column DESC [modified]memberMember 31061887 Nov '08 - 18:16 
Hi,
 
I have the same problem; Did you find a solution?
 
Thank you,
Rune
 

I removed the following statement in "private void BindGrid()" and it is running:
 
if ( ViewState["SortExpression"] != null )
              {
                     dv.Sort = ViewState["SortExpression"].ToString() + " DESC";
              }
              else
              {
                     <code>//dv.Sort = gv1.DefaultSortExpression + " DESC";</code>
              }

 
modified on Saturday, November 8, 2008 12:26 AM

GeneralSaifi great jobmemberwasimsharp5 Jun '08 - 0:04 
hi Saifi i read ur article it is real goood man keep it up.
but the think that i like most is the who is test singh Laugh | :laugh:
just joking but it is realy good
 
wasim khan

Generalgreat jobmemberMember 39207367 May '08 - 19:41 
sorting is not working for me..
 
Property or indexer 'System.Web.UI.WebControls.GridView.SortDirection' cannot be assigned to -- it is read only
what could be the reason
 
thanks
Nawal
GeneralRe: great jobmemberSaifi Hasan9 May '08 - 2:38 
well this Grid do not support Bi-directional sorting. also make sure to give SortExpression
 
Nobody is perfect i'm Nobody

GeneralRe: great jobmemberSaifi Hasan24 Jul '08 - 13:09 
well for sorting you mus use DataView Sort method, GridView.SortDirection is readonly property so we are not suppose to assign it. for ref please see the test app in which DataView has been used
 
Nobody is perfect i'm Nobody

GeneralHi Friendmemberrao_2117 May '08 - 4:40 
Do i need to register in DLL in to GAC / Reg. I am getting error when i place control into desgin page
 
R Srinivasa Rao

GeneralRe: Hi FriendmemberSaifi Hasan9 May '08 - 0:40 
no u dont need it to register in GAC, just make a add reference
 
Nobody is perfect i'm Nobody

GeneralHi Buddymemberrao_2117 May '08 - 2:57 
How to confirgure................i could not able to run the sample...
 
R Srinivasa Rao

GeneralGud work buddymemberHemJoshi6 May '08 - 1:43 
Gud work buddy
Generalvery useful articlememberVivek_Bhat6 May '08 - 0:01 
A very useful article....5 from my side

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web04 | 2.6.130523.1 | Last Updated 5 May 2008
Article Copyright 2008 by Saifi Hasan
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid