Restricting the number of rows in a dataview when binding to a repeater
The problem
I needed to restrict the number of items bound to an asp:repeater. Basically I never wanted more than 10 items to be displayed.
Options
The right thing to do would be to restrict the number of items at the database level using Set RowCount or top 10.
In this instance, it wasn't an option and the lack of a RowCount feature on the DataView object left me needing to find another solution.
The Solution
After some searching, I came across a bit of code which proved helpful. The following code makes allows me to pass a DataView into an enumerable object which returns only the number of rows I'm interested in.
Example Use
myRepeater.DataSource = new FilterRows(myDataView, 10);
The Enumerable Object
using System;
using System.Data;
using System.Web.Security;
using System.Collections;
/// <summary>
/// Summary description for FilterRows
/// </summary>
public class FilterRows : IEnumerable
{
DataView dataView;
private int rowsToShow;
public FilterRows(DataView dataView, int rowsToShow)
{
this.rowsToShow = rowsToShow;
this.dataView = dataView;
}
public IEnumerator GetEnumerator()
{
return new PageOfData(this.dataView.GetEnumerator(), this.rowsToShow);
}
internal class PageOfData : IEnumerator
{
private IEnumerator e;
private int cnt = 0;
private int rowsToShow;
internal PageOfData(IEnumerator e, int rowsToShow)
{
this.rowsToShow = rowsToShow;
this.e = e;
}
public object Current
{
get { return e.Current; }
}
public bool MoveNext()
{
// If we've hit out limit return false
if (cnt >= rowsToShow)
return false;
// Track the current row
cnt++;
return e.MoveNext();
}
public void Reset()
{
e.Reset();
cnt = 0;
}
}
}
| Author |
: Paul Hayman |
| Published |
: 16 August 2006 |
Paul is the COO of kwiboo ltd consultant and has more than a decade of IT consultancy experience. He has consulted for a number of blue chip companies and has been exposed to the folowing sectors: Utilities, Telecommunications, Insurance, Media, Investment Banking, Leisure, Legal, CRM, Pharmaceuticals, Interactive Gaming, Mobile Communications, Online Services.
Paul is the COO and co-founder of kwiboo (http://www.kwiboo.com/) and is also the creator of GeekZilla.