Alex Feinman posted code on how to sort a DataGrid in C# for the .NET Compact Framework a while ago on the newsgroups. The only improvement I needed to make was to support TableStyles. One line of code later I had the following;
using
System.Windows.Forms;
using System.Data;
public
static void SortDataGrid(object sender, System.Windows.Forms.MouseEventArgs e)
{
DataGrid.HitTestInfo hitTest;
DataTable dataTable;
DataView dataView;
string columnName;
DataGrid dataGrid;
// Use only left mouse button clicks.
if (e.Button == MouseButtons.Left)
{
// Set dataGrid equal to the object that called this event handler.
dataGrid = (DataGrid)sender;
// Perform a hit test to determine where the mousedown event occured.
hitTest = dataGrid.HitTest(e.X, e.Y);
// If the MouseDown event occured on a column header,
// then perform the sorting operation.
if (hitTest.Type == DataGrid.HitTestType.ColumnHeader)
{
// Get the DataTable associated with this datagrid.
dataTable = (DataTable)dataGrid.DataSource;
// Get the DataView associated with the DataTable.
dataView = dataTable.DefaultView;
// Get the name of the column that was clicked.
if(dataGrid.TableStyles.Count != 0)
columnName = dataGrid.TableStyles[0].GridColumnStyles[hitTest.Column].MappingName;
else
columnName = dataTable.Columns[hitTest.Column].ColumnName;
// If the sort property of the DataView is already the current
// column name, sort that column in descending order.
// Otherwise, sort on the column name.
if (dataView.Sort == columnName)
dataView.Sort = columnName + " DESC";
else
dataView.Sort = columnName;
}
}
}
private void dgDataGrid_MouseUp(object sender, System.Windows.Forms.MouseEventArgs e)
{
if(dgDataGrid.VisibleRowCount == 0) return;
SortDataGrid(sender, e);
dgDataGrid.Select(dgDataGrid.CurrentRowIndex);
}