Luis Valencia
Luis Valencia

Reputation: 33988

Modify custom query to paginate with a gridview

I have the following code which executes a custom query to the database. The queries definition is stored on a table, but the users wont enter pagination.

Because it can return 10,000 rows or more I need to paginate by modifying the query.

QuerySql= "select * from requestbases where currentstatus == 'Approved 1' and ammountwithvat>100000"

It returns 10,000 rows.

My code:

 public DataTable GetGenericResults(string strsql)
            {
                using(var connection = (SqlConnection)_context.Database.Connection)
                {
                    var adapter = new SqlDataAdapter(strsql, connection);
                    var results = new DataSet();
                    adapter.Fill(results, "Results");
                    return results.Tables["Results"];
                }
            }




var datatable = RequestBaseBL.GetGenericResults(query.QuerySql);
                    if (datatable.Rows.Count > 0)
                    {
                        LblCount.Text = datatable.Rows.Count + " records";
                        PanelResults.Visible = true;
                        GrvCustomResults.Visible = true;
                        GrvCustomResults.DataSource = datatable;
                        GrvCustomResults.DataBind();

Upvotes: 0

Views: 183

Answers (1)

Mike Miller
Mike Miller

Reputation: 16575

I would use the query in a CTE, like this

WITH MyPagedData as (
SELECT *,
ROW_NUMBER() OVER(ORDER BY IdentityCol DESC) as RowNum,
ROW_NUMBER() OVER(ORDER BY IdentityCol ASC) as InverseRowNum
FROM requestbases where currentstatus == 'Approved 1' and ammountwithvat > 100000
)

SELECT * from MyPagedData where RowNum between @StartIndex and @StartIndex + 20  

So this assumes that you are able to write some code that inserts the RowNumber bit in the right place of the select statement and also that you are using MSSQL 2005. You may also need to adjust the IdentityCol bit if you haven't got identity columns.

So StartIndex is the last shown item of data and 20 is the amount of items you want on a page. The total amount of items is the sum of RowNum and InverseRowNum -1.

Upvotes: 1

Related Questions