Click here to Skip to main content
Licence 
First Posted 5 Jan 2006
Views 64,897
Bookmarked 47 times

Page DataGrid with huge count of records

By | 5 Jan 2006 | Article
Optimizing paging in DataGrids.
 
Part of The SQL Zone sponsored by
See Also

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):

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:

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:

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.

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;
}
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:

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

About the Author

Kyrylo Yatsenko

Web Developer
SOCIETE GENERALE CREDIT INVESTMENT BANKING
France France

Member

Kyrylo has started his IT career as software developer. Shortly he became Team Lead developer leading the projects based on MS .NET Framework technology.
 
Today he is working for SOCIETE GENERALE CIB, trying to combine his experience of software developer with bank's activities on electronic markets.

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
Generaluse with extreme caution PinmemberMember 339949215:27 16 May '10  
Generala problem with it Pinmemberwuerlang16:34 3 May '06  
GeneralRe: a problem with it Pinmemberlauralucas10:49 2 Aug '06  
GeneralRe: a problem with it PinmemberKirill Yatsenko21:41 2 Aug '06  
GeneralRe: a problem with it PinmemberKirill Yatsenko21:40 2 Aug '06  
GeneralRe: a problem with it [modified] Pinmemberlauralucas3:30 3 Aug '06  
Of course, i'm not critizising your work, I think it serves its purpose. Thanks for the article! My own workaround? I know, but maybe you have a hint that would help me? Sigh | :sigh:
 

 
-- modified at 11:00 Thursday 3rd August, 2006
I have it! the last part of the sql query must look like this:
 
ORDER BY nickname asc, id asc) ORDER BY nickname asc, id asc
 
for repeated nickname, and unique id
 
Smile | :)
Generalnot transaction-save Pinmembermfritz22:54 10 Jan '06  
GeneralRe: not transaction-save PinmemberKirill Yatsenko4:27 3 Aug '06  
Generalthe following is a much better solution... Pinmemberneilmcguigan7:43 9 Jan '06  
GeneralRe: the following is a much better solution... PinmemberKirill Yatsenko2:04 10 Jan '06  
Generalsql script vs stored procedure Pinmembermbaskey1:16 6 Jan '06  
GeneralGood article Pinmemberbubskirat16:02 5 Jan '06  

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
Web02 | 2.5.120529.1 | Last Updated 5 Jan 2006
Article Copyright 2006 by Kyrylo Yatsenko
Everything else Copyright © CodeProject, 1999-2012
Terms of Use
Layout: fixed | fluid