Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / C#

An extended version of DataGridView with paging

2.07/5 (6 votes)
20 Jun 2007CPOL 1   576  
This does what it says on the tin. I was inspired to extend the DataGridView control after reading a similar article by D Strauss.

Screenshot - PagingDataGridView_scr.jpg

Introduction

This is my first CodeProject article. This control is a simple extension of the DataGridView control that ships with Visual Studio .NET. Before anyone comes back at me with comments about optimization of code etc., I may well update it in the future.

Background

After reading D Straus' article about making a DataGridView page, I thought I'd extend it to include paging.

Using the code

The use of this control is pretty straightforward. Download the source, compile the DLL, import it into your Toolbox in Designer mode in VS, and away you go.

The main methods are:

  • GoToNextPage()
  • oToLastPage()
  • GoToPreviousPage()
  • GoToFirstPage()
  • GoToPageNumber(int pageno)
C#
public void GoToPageNumber(int n)
{
    DataSet dsTempSubSet = new DataSet();
    DataRow[] rows = new DataRow[RowsPerPage];
    
    if (n == 1)
    {
        GoToFirstPage();
    }
    if ((0 < n) && (n <= GetTotalPages()))
    {
        int PageIndex = (n - 1) * RowsPerPage;
        if (PageIndex >= dsTemp.Tables[0].Rows.Count)
        {
            GoToFirstPage();
        }
        else
        {
            int WholePages = dsTemp.Tables[0].Rows.Count / RowsPerPage;
            if ((dsTemp.Tables[0].Rows.Count % RowsPerPage) != 0 && n == GetTotalPages())
            {
                rows = new DataRow[dsTemp.Tables[0].Rows.Count - 
                                       (WholePages * RowsPerPage)];
            }
            for (int i = 0, i2 = PageIndex; i < rows.Length && i2 < 
                                 dsTemp.Tables[0].Rows.Count; i2++, i++)
            {
                rows[i] = dsTemp.Tables[0].Rows[i2];
            }
            dsTempSubSet.Merge(rows);
            bindingSource1.DataSource = dsTempSubSet.Tables[0];
            this.DataSource = bindingSource1;
            CurrentPage = n;
        }
    }
}

History

  • 1.1 - 21-June-2007: Optimized code, most nav methods now use GoToPageNumber(int).
  • 1.0 - 20-June-2007: Initial upload.

License

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