Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version
  1. Set the DataGridView's SelectionMode property to FullColumnSelect or ColumnHeaderSelect.
  2. Set the SortMode property of the columns that can be sorted to Automatic.
  3. Handle the ColumnHeaderMouseClick event of the DataGridView.
  4. In the event handler, determine which column header was clicked by examining the e.ColumnIndex property of the DataGridViewCellMouseEventArgs parameter.
  5. Get the underlying DataGridViewColumn object for the clicked column header using the Columns[e.ColumnIndex] property.
  6. Call the Sort method of the DataGridView with the DataGridViewColumn and the sort direction as arguments.
  7. Optionally, set the SortGlyphDirection property of the clicked column header to display an arrow to indicate the sort direction.

Example code:

private void dataGridView1_ColumnHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e)
{
    DataGridViewColumn column = dataGridView1.Columns[e.ColumnIndex];
    if (column.SortMode != DataGridViewColumnSortMode.Automatic)
    {
        return;
    }

    ListSortDirection direction = ListSortDirection.Ascending;

    if (column.HeaderCell.SortGlyphDirection == SortOrder.Ascending)
    {
        direction = ListSortDirection.Descending;
    }

    dataGridView1.Sort(column, direction);

    // Optionally, set the sort glyph direction
    foreach (DataGridViewColumn col in dataGridView1.Columns)
    {
        if (col != column)
        {
            col.HeaderCell.SortGlyphDirection = SortOrder.None;
        }
    }

    column.HeaderCell.SortGlyphDirection = direction == ListSortDirection.Ascending ?
        SortOrder.Ascending : SortOrder.Descending;
}