Click here to Skip to main content
Licence CPOL
First Posted 9 Nov 2006
Views 50,361
Downloads 509
Bookmarked 39 times

DataGrid Paging Using DataReader - C# Windows Forms

By | 9 Nov 2006 | Article
DataGrid paging using DataReader.
 
Part of The SQL Zone sponsored by
See Also

Sample Image - DataGridPaging_DataReader.gif

Introduction

This is an example of Windows Forms DataGrid paging using C#. I have used a Microsoft SQL Server 2000 database in the demo.

Using the code

Create a table:

CREATE TABLE tblEmp (E_ID int PRIMARY KEY, E_Name varchar(60), 
                     E_Salary money, E_DOJ datetime)
GO

Public variables:

// Protected Connection.
protected SqlConnection mcnSample;

// Page
private int mintTotalRecords = 0;
private int mintPageSize = 0;
private int mintPageCount = 0;
private int mintCurrentPage = 1;

// Connection String
protected const string CONNECTION_STRING = 
          "Server=localhost;UID=sa;PWD=;Database=Sample";

The fillGrid() method:

private void fillGrid()
{
    // For Page view.
    this.mintPageSize = int.Parse(this.tbPageSize.Text);
    this.mintTotalRecords = getCount();
    this.mintPageCount = this.mintTotalRecords / this.mintPageSize;
    
    // Adjust page count if the last page contains partial page.
    if (this.mintTotalRecords % this.mintPageSize > 0)
        this.mintPageCount++;

    this.mintCurrentPage = 0;

    loadPage();
}

The getCount() method: this method gets the record count much faster than the SELECT COUNT(*) statement does.

private int getCount()
{
    // This select statement is very fast compare to SELECT COUNT(*)
    string strSql = "SELECT Rows FROM SYSINDEXES WHERE " + 
                    "Id = OBJECT_ID('tblEmp') AND IndId < 2";
    int intCount = 0;

    SqlCommand cmd = this.mcnSample.CreateCommand();
    cmd.CommandText = strSql;

    intCount = (int) cmd.ExecuteScalar();
    cmd.Dispose();

    return intCount;
}

The loadPage() method:

private void loadPage()
{
    string strSql = "";
    int intSkip = 0, i = 0;
    SqlDataReader dr;
    DataSet ds;
    DataTable dt;

    intSkip = (this.mintCurrentPage * this.mintPageSize);

    strSql = "SELECT * FROM tblEmp";

    SqlCommand cmd = this.mcnSample.CreateCommand();
    cmd.CommandText = strSql;

    dr = cmd.ExecuteReader(); 
    ds = new DataSet();

    dt = ds.Tables.Add("tblEmp");

    // Add the table columns.
    for (i = 0; i < dr.FieldCount; i++) 
        dt.Columns.Add(dr.GetName(i), dr.GetFieldType(i)); 

    int intIdx = 0;
    while (dr.Read())
    {
        if (intIdx >= intSkip)
        {
            DataRow r = dt.NewRow();

            // Assign DataReader values to DataRow.
            for (i = 0; i < dr.FieldCount; i++)
                r[i] = dr[i];

            dt.Rows.Add(r);
        }

        if ((intIdx - intSkip) >= (this.mintPageSize - 1))
            break;

        intIdx++;
    }

    dr.Close();

    // Populate Data Grid
    this.dgEmp.DataSource = ds.Tables["tblEmp"].DefaultView;

    // Show Status
    this.lblStatus.Text = (this.mintCurrentPage + 1).ToString() + 
                           " / " + this.mintPageCount.ToString();

    cmd.Dispose();
    ds.Dispose();
}

Here is the code for page navigation:

private void goFirst()
{
    this.mintCurrentPage = 0;

    loadPage();
}

private void goPrevious()
{
    if (this.mintCurrentPage == this.mintPageCount)
        this.mintCurrentPage = this.mintPageCount - 1;

    this.mintCurrentPage--;

    if (this.mintCurrentPage < 1) 
        this.mintCurrentPage = 0;

    loadPage();
}

private void goNext()
{
    this.mintCurrentPage++;

    if (this.mintCurrentPage > (this.mintPageCount - 1))
        this.mintCurrentPage = this.mintPageCount - 1;

    loadPage();
}

private void goLast()
{
    this.mintCurrentPage = this.mintPageCount - 1;

    loadPage();
}

History

  • Released on November 9th 2006.

License

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

About the Author

Manoh

Team Leader

India India

Member



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. (secure sign-in)
 
Search this forum  
 FAQ
    Noise  Layout  Per page   
  Refresh
Generalsimple and functional PinmemberFernandoMartin3:43 16 Sep '09  

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

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Mobile
Web01 | 2.5.120517.1 | Last Updated 9 Nov 2006
Article Copyright 2006 by Manoh
Everything else Copyright © CodeProject, 1999-2012
Terms of Use
Layout: fixed | fluid