Problem: Sorting for GridView/ObjectDataSource changes depending on page

Posted by user148298 on Stack Overflow See other posts from Stack Overflow or by user148298
Published on 2009-08-05T04:43:39Z Indexed on 2010/03/19 8:01 UTC
Read the original article Hit count: 388

Filed under:
|
|

I have a GridView tied to an ObjectDataSource using paging. The paging works fine, except that the sort order changes depending on which page of the results is being viewed. This causes items to reappear on subsequent pages among other issues. I traced the problem to my DAL, which reads a page at a time and then sorts it. Obviously the sorting is going to change as the result set size changes. Is there an improvement to this algorithm. I would like to use a datareader if possible:

    [System.ComponentModel.DataObjectMethod(System.ComponentModel.DataObjectMethodType.Select)]
    public static WordsCollection LoadForCriteria(string sqlCriteria, int maximumRows, int startRowIndex, string sortExpression)
    {
        //DEFAULT SORT EXPRESSION
        if (string.IsNullOrEmpty(sortExpression)) sortExpression = "OrderBy";
        //CREATE THE DYNAMIC SQL TO LOAD OBJECT
        StringBuilder selectQuery = new StringBuilder();
        selectQuery.Append("SELECT");
        if (maximumRows > 0) selectQuery.Append(" TOP " + (startRowIndex + maximumRows).ToString());
        selectQuery.Append(" " + Words.GetColumnNames(string.Empty));
        selectQuery.Append(" FROM sw_Words");
        string whereClause = string.IsNullOrEmpty(sqlCriteria) ? string.Empty : " WHERE " + sqlCriteria;
        selectQuery.Append(whereClause);
        selectQuery.Append(" ORDER BY " + sortExpression);
        Database database = Token.Instance.Database;
        DbCommand selectCommand = database.GetSqlStringCommand(selectQuery.ToString());
        //EXECUTE THE COMMAND
        WordsCollection results = new WordsCollection();
        int thisIndex = 0;
        int rowCount = 0;
        using (IDataReader dr = database.ExecuteReader(selectCommand))
        {
            while (dr.Read() && ((maximumRows < 1) || (rowCount < maximumRows)))
            {
                if (thisIndex >= startRowIndex)
                {
                    Words varWords = new Words();
                    Words.LoadDataReader(varWords, dr);
                    results.Add(varWords);
                    rowCount++;
                }
                thisIndex++;
            }
            dr.Close();
        }
        return results;
    }

© Stack Overflow or respective owner

Related posts about gridview

Related posts about objectdatasource