Craig Gibbons' Lifeblog lifeblog://


Custom paging using the PagedDataSource class in C#.NET

Paging is a problem which has plagued developers for years. During that time, many ingenious (and some not so ingenious) solutions to the problem have been thought up, but in my estimation, none are as elegant as the solution presented here. I'm the type of coder who will always try to find a code snippet or a component before attempting something complex. There is a certain joy in writing something tough, but also a lot of time invested and in any case why reinvent the wheel? When I was looking for a solution to custom paging, I was delighted to find exactly the thing I was looking for, that being, the DataGrid paging functionality in a separate class. The use of this class is pretty straight forward so I present the following code snippet as illustration of it's use.

PagedDataSource pagedData = new PagedDataSource();

pagedData.AllowPaging = true;
pagedData.PageSize = 10;
pagedData.DataSource = GetDataSource();

dataGrid.DataSource = pagedData;

Pretty easy stuff all round, but devastatingly useful. Note that I have omitted the GetDataSource() routine for brevity, but whatever data source you pass, it must implement IEnumerable. A few examples of objects that implement IEnumerable are ArrayList, DataView, HashTable and even String. Note that a custom collection can also be used. From there, actually doing the paging is pretty straight forward, simply create buttons and hook up the Click or Command events. Note that "PageIndex" as used below is stored as a ViewState variable, but can be implemented as a QueryString parameter if you prefer.

protected void btnBack_Command(object sender, CommandEventArgs e) {
 pagedData.CurrentPageIndex = PageIndex;


protected void btnNext_Command(object sender, CommandEventArgs e) {
 pagedData.CurrentPageIndex = PageIndex;


Thats about all there is to it. There are some other useful properties of the PagedDataSource class, but I shall leave you to explore the documentation at your leisure. One last thing to note is that this approach is not recommended for very large datasets because the GetDataSource() routine will still fetch all the records from the database, the PagedDataSource class merely shows 'n' at a time. If you intend displaying and paging many hundreds or thousands of records, you might consider a different approach where your SQL returns only a subset of the data each time, thus minimising the data and consequent memory requirements on each request.

Happy coding!

Filed under: Tech Leave a comment
Comments (0) Trackbacks (0)

No comments yet.

Leave a comment

No trackbacks yet.