Click here to Skip to main content
15,891,431 members
Articles / Web Development / ASP.NET
Article

Page DataGrid with huge count of records

Rate me:
Please Sign up or sign in to vote.
2.42/5 (11 votes)
5 Jan 20061 min read 81.3K   47   12
Optimizing paging in DataGrids.

Introduction

Many of you are familiar with paging in an ASP.NET DataGrid. And, also, most of you must know that standard methods of paging in the .NET Framework does not work (of course, we should not blame the technology for that). So in this article, I would like to tell you about a fast paging method for SQL query results with a large number of records. Other articles of the same sort can be found at this site, but I want to share my thoughts in a shorter form. Please enjoy my short, but very useful (as I can assume) article.

Using the code

For the methods below you need to define what tables and columns you want to retrieve from the DB. Also, you have to determine what join of the tables to use and what order to be provided. So, let's begin.

This method is used to get the items count from the from the query (is necessary for paging, will be illustrated later):

C#
public int GetRecordCount( string tableName )
{
    string sql = "select count(*) from "+ tableName;
    return Convert.ToInt32(executeScalar(sql));
}

This method is used to create an SQL query for the database:

C#
public string CreateSql(int pageNumber, int pageSize, string primaryKey, 
                        string fieldNames, string fromTables, 
                        string condition, string orderBy)
{
    string sql = " SELECT TOP "+pageSize+" "+ 
                 fieldNames+" FROM "+ fromTables +" ";
    if (condition!=null && !string.Empty.Equals(condition))
    {
        if (!condition.ToLower().Trim().StartsWith("where"))
        {
            sql += " where ";
        }
        sql += condition + " and ";
        
    }
    if (sql.ToLower().IndexOf("where")==-1)
        sql+= " where ";

    sql+= " " +primaryKey +" NOT IN " +
          " (SELECT TOP "+(pageNumber*pageSize)+ 
          " "+primaryKey+" FROM " + fromTables+" ";
    if (condition!=null && !string.Empty.Equals(condition))
    {
        if (!condition.ToLower().Trim().StartsWith("where"))
        {
            sql += " where ";
        }
        sql += condition;
    }

    if (orderBy!=null && !string.Empty.Equals(orderBy))
    {
        sql+= " ORDER BY "+orderBy+") "+
            " ORDER BY "+orderBy;
    }
    else
    {
        sql+=")";
    }
    return sql;
}

Running the SQL query:

C#
public void RunSql(string sqlString, 
            out SqlDataReader dataReader)
{
    SqlCommand cmd = CreateSqlCommand(sqlString,  null);
    dataReader = cmd.ExecuteReader();
}

Two overloaded methods of query creation are provided. The first one is used when the total number of records in the query (not in one page) is known, and the second in the other case.

C#
public SqlDataReader GetListByPage (int pageNumber, int pageSize, 
                     string primaryKey, string fieldNames, 
                     string fromTables, string condition, string orderBy)
{
    string sql= CreateSql (pageNumber,pageSize, primaryKey, 
                fieldNames,fromTables,condition,orderBy);
    SqlDataReader dr;
    RunSql(sql, out dr);
    return dr;
}
C#
public SqlDataReader GetListByPage (out int rowcount, int pageNumber, 
                     int pageSize, string primaryKey, string fieldNames, 
                     string fromTables, string condition, string orderBy)
{
    string countSql = fromTables;
    if (condition!=null && !string.Empty.Equals(condition))
    {

        if (!condition.ToLower().Trim().StartsWith("where"))
        {
            countSql += " where ";
        }
        countSql += condition;
    }
    rowcount = GetRecordCount(countSql);
    return GetListByPage(pageNumber, pageSize, primaryKey, 
                         fieldNames, fromTables, condition, orderBy);        
}

Here, is a small sample of using this code:

C#
myDataGrid.DataSource = db.GetListByPage(out rowcount, 
                        PageIndex,myDataGrid.PageSize, 
                        "KeyField",fieldNames,tables,
                        search,OrderBy);
myDataGrid.VirtualItemCount = rowcount;
myDataGrid.CurrentPageIndex = PageIndex;

And don't forget to set the AllowCustomPaging property to true in your DataGrid. That's it for now.

Special Thanks

I want to express my special thanks to Olexander Rudyy for his huge help in my last project!

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here



Comments and Discussions

 
Generaluse with extreme caution Pin
SeanKuehnel16-May-10 15:27
SeanKuehnel16-May-10 15:27 
Generala problem with it Pin
wuerlang3-May-06 16:34
wuerlang3-May-06 16:34 
GeneralRe: a problem with it Pin
lauralucas2-Aug-06 10:49
lauralucas2-Aug-06 10:49 
GeneralRe: a problem with it Pin
Ryzhiy2-Aug-06 21:41
Ryzhiy2-Aug-06 21:41 
GeneralRe: a problem with it Pin
Ryzhiy2-Aug-06 21:40
Ryzhiy2-Aug-06 21:40 
GeneralRe: a problem with it [modified] Pin
lauralucas3-Aug-06 3:30
lauralucas3-Aug-06 3:30 
Generalnot transaction-save Pin
mfritz10-Jan-06 22:54
mfritz10-Jan-06 22:54 
GeneralRe: not transaction-save Pin
Ryzhiy3-Aug-06 4:27
Ryzhiy3-Aug-06 4:27 
Generalthe following is a much better solution... Pin
neilmcguigan9-Jan-06 7:43
neilmcguigan9-Jan-06 7:43 
GeneralRe: the following is a much better solution... Pin
Ryzhiy10-Jan-06 2:04
Ryzhiy10-Jan-06 2:04 
I have looked through the referenced article. I must say that it is not that general as all 5 variants require specific setup for EACH data array. At the end, it's up to the end user to decide which method to use.

The strongest part of the code proposed is its simplicity Smile | :)

For more info please advice
Generalsql script vs stored procedure Pin
mbaskey6-Jan-06 1:16
mbaskey6-Jan-06 1:16 
GeneralGood article Pin
buboi_navaja5-Jan-06 16:02
buboi_navaja5-Jan-06 16:02 

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

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