The datagrid has an option to sort the grid on a column. Every column in the grid has has SortExpression property. When you click the column header the SortCommand event is fired. In the parameters of that event you can get the SortExpression of the column whose header was clicked.
That’s very nice but the moment you disable the grid’s viewstate the event no longer fires. The viewstate of a datagrid gets very big, it’s something you want to keep disabled. But the sorting option is nice. I found the folowing workaround.
When the page posts back it is not a great problem to find out which control caused the postback. The names of the sortlinkbuttons all begin with the name of the datagrid. The second part of the name is the grid’s header and part of the third name is the column. So you can check (in page_prerender,or page_load) if and which column was clicked
// In case of column header click
// Request.Form["__EVENTTARGET"] will look like "DataGrid1:_ctl1:_ctl3"
char[] splitters = {':'};
string[] pbCtrl = Request.Form["__EVENTTARGET"].Split(splitters);
if (pbCtrl[0] == DataGrid1.ID)
{
// Column ID's is 1-based !
int columnClicked = int.Parse(pbCtrl[2].Substring(4)) + 1;
sortOrder = DataGrid1.Columns[columnClicked].SortExpression;
}
The SortExpression is not in the viewstate and fully available.
It is a hack. But works like a charm.