It can be done without the use of View State or Session. Current order can be determined based on value in first and last row in the column we sort by:
protected void gvItems_Sorting(object sender, GridViewSortEventArgs e)
{
GridView grid = sender as GridView; // get reference to grid
SortDirection currentSortDirection = SortDirection.Ascending; // default order
// get column index by SortExpression
int columnIndex = grid.Columns.IndexOf(grid.Columns.OfType<DataControlField>()
.First(x => x.SortExpression == e.SortExpression));
// sort only if grid has more than 1 row
if (grid.Rows.Count > 1)
{
// get cells
TableCell firstCell = grid.Rows[0].Cells[columnIndex];
TableCell lastCell = grid.Rows[grid.Rows.Count - 1].Cells[columnIndex];
// if field type of the cell is 'TemplateField' Text property is always empty.
// Below assumes that value is binded to Label control in 'TemplateField'.
string firstCellValue = firstCell.Controls.Count == 0 ? firstCell.Text : ((Label)firstCell.Controls[1]).Text;
string lastCellValue = lastCell.Controls.Count == 0 ? lastCell.Text : ((Label)lastCell.Controls[1]).Text;
DateTime tmpDate;
decimal tmpDecimal;
// try to determinate cell type to ensure correct ordering
// by date or number
if (DateTime.TryParse(firstCellValue, out tmpDate)) // sort as DateTime
{
currentSortDirection =
DateTime.Compare(Convert.ToDateTime(firstCellValue),
Convert.ToDateTime(lastCellValue)) < 0 ?
SortDirection.Ascending : SortDirection.Descending;
}
else if (Decimal.TryParse(firstCellValue, out tmpDecimal)) // sort as any numeric type
{
currentSortDirection = Decimal.Compare(Convert.ToDecimal(firstCellValue),
Convert.ToDecimal(lastCellValue)) < 0 ?
SortDirection.Ascending : SortDirection.Descending;
}
else // sort as string
{
currentSortDirection = string.CompareOrdinal(firstCellValue, lastCellValue) < 0 ?
SortDirection.Ascending : SortDirection.Descending;
}
}
// then bind GridView using correct sorting direction (in this example I use Linq)
if (currentSortDirection == SortDirection.Descending)
{
grid.DataSource = myItems.OrderBy(x => x.GetType().GetProperty(e.SortExpression).GetValue(x, null));
}
else
{
grid.DataSource = myItems.OrderByDescending(x => x.GetType().GetProperty(e.SortExpression).GetValue(x, null));
}
grid.DataBind();
}