Click here to Skip to main content
6,305,776 members and growing! (16,201 online)
Email Password   helpLost your password?
Web Development » ASP.NET Controls » General     Intermediate

Page DataGrid with huge count of records

By Kyrylo Yatsenko

Optimizing paging in DataGrids.
C#, SQL, Windows, .NET, ASP.NET, Visual Studio, ADO.NET, WebForms, DBA, Dev
Posted:5 Jan 2006
Views:53,271
Bookmarked:38 times
Announcements
Loading...
 
Search    
Advanced Search
printPrint   Broken Article?Report       add Share
  Discuss Discuss   Recommend Article Email
11 votes for this article.
Popularity: 2.66 Rating: 2.55 out of 5
3 votes, 27.3%
1
3 votes, 27.3%
2
3 votes, 27.3%
3
1 vote, 9.1%
4
1 vote, 9.1%
5

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


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.
Occupation: Web Developer
Company: SOCIETE GENERALE CREDIT INVESTMENT BANKING
Location: France France

Other popular ASP.NET Controls articles:

Article Top
You must Sign In to use this message board.
FAQ FAQ 
 
Noise Tolerance  Layout  Per page   
 Msgs 1 to 11 of 11 (Total in Forum: 11) (Refresh)FirstPrevNext
Generala problem with it Pinmemberwuerlang17:34 3 May '06  
GeneralRe: a problem with it Pinmemberlauralucas11:49 2 Aug '06  
GeneralRe: a problem with it PinmemberKirill Yatsenko22:41 2 Aug '06  
GeneralRe: a problem with it PinmemberKirill Yatsenko22:40 2 Aug '06  
GeneralRe: a problem with it [modified] Pinmemberlauralucas4:30 3 Aug '06  
Generalnot transaction-save Pinmembermfritz23:54 10 Jan '06  
GeneralRe: not transaction-save PinmemberKirill Yatsenko5:27 3 Aug '06  
Generalthe following is a much better solution... Pinmemberneilmcguigan8:43 9 Jan '06  
GeneralRe: the following is a much better solution... PinmemberKirill Yatsenko3:04 10 Jan '06  
Generalsql script vs stored procedure Pinmembermbaskey2:16 6 Jan '06  
GeneralGood article Pinmemberbubskirat17:02 5 Jan '06  

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

PermaLink | Privacy | Terms of Use
Last Updated: 5 Jan 2006
Editor: Smitha Vijayan
Copyright 2006 by Kyrylo Yatsenko
Everything else Copyright © CodeProject, 1999-2009
Web16 | Advertise on the Code Project