How to hide a DataPager control when there is only one page of data

When you are paging data in a ListView control using the DataPager, by default, the DataPager will be shown even if there is only one page of data. So, if you're using a NumericPagerField for example, you're going to end up with a text showing 1 in your page. So, in this cases, you might want to hide the DataPager control.
One way of achieving this is to change the visibility of the control on the DataBound event of the ListView control. For example:

 protected void ListView1_DataBound(object sender, EventArgs e)
{
  DataPager1.Visible = (DataPager1.PageSize < DataPager1.TotalRowCount);
}

In the example above, the DataPager is not inside the ListView control. If you place the DataPager inside the LayoutTemplate, then you have to tweak the code a little bit to find the control inside ListView. For example:

 protected void ListView1_DataBound(object sender, EventArgs e)
{
  DataPager pager = (DataPager) ListView1.FindControl("DataPager1");
  pager.Visible = (pager.PageSize < pager.TotalRowCount);
}

This way you can control whether you want the pager displayed or not.

Comments

  • Anonymous
    January 13, 2009
    Nice! a simple yet elegant solution!

  • Anonymous
    February 13, 2009
    Great Example. I like your short and straightforward writing style. It worked for me - Thanks!

  • Anonymous
    February 18, 2009
    I was looking for a good code for a while. This looks great. Thanx.

  • Anonymous
    February 22, 2010
    Nice and clean ! I was wondering if there's a way to do it using styles rather than c# code. Thanks. Sanaa

  • Anonymous
    June 17, 2010
    Thanks, but this fails if ListView is empty. You should surround it with if (ListView1.Items.Count > 0).

  • Anonymous
    October 12, 2011
    Any idea for an MVVM Version?

  • Anonymous
    June 26, 2012
    Another slightly more secure solution.. protected void ListView1_ItemCreated( object sender, ListViewItemEventArgs e ) {    if ( e.Item.ItemType == ListViewItemType.EmptyItem )    {      DataPager1.Visible = false;    } }

  • Anonymous
    June 25, 2014
    Thank you very much for elegant solution :) It helped me very much !

  • Anonymous
    January 02, 2016
    Thanks for showing which event to use for visibility - I did the same coding, but couldn't guess the event.