1 | initial version |
SelectionMode
property to FullColumnSelect
or ColumnHeaderSelect
.SortMode
property of the columns that can be sorted to Automatic
.ColumnHeaderMouseClick
event of the DataGridView.e.ColumnIndex
property of the DataGridViewCellMouseEventArgs
parameter.DataGridViewColumn
object for the clicked column header using the Columns[e.ColumnIndex]
property.Sort
method of the DataGridView with the DataGridViewColumn
and the sort direction as arguments.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;
}