Ask Your Question
0

What steps should be taken to activate sorting for a DataGridView when the user selects a column header?

asked 2022-10-01 11:00:00 +0000

nofretete gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
0

answered 2022-05-20 13:00:00 +0000

qstack gravatar image
  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;
}
edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2022-10-01 11:00:00 +0000

Seen: 12 times

Last updated: May 20 '22