DataGridView.ColumnHeaderMouseClick Event


Occurs when the user clicks a column header.

Namespace:   System.Windows.Forms
Assembly:  System.Windows.Forms (in System.Windows.Forms.dll)

Public Event ColumnHeaderMouseClick As DataGridViewCellMouseEventHandler

For more information about handling events, see NIB: Consuming Events.

When a column heading is clicked in a DataGridView, the default behavior is to order the grid rows based on the clicked column, or to reverse the sort order if the grid is already sorted by the clicked column. The following code example demonstrates how to use this event to perform a programmatic sort that emulates the default behavior of clicking a DataGridViewColumnHeaderCell when the default behavior has been disabled. In this example, theSelectionMode is set to ColumnHeaderSelect, so clicking the DataGridViewColumnHeaderCell selects the contents of the column. For the example code to function as intended, the default column header click behavior needs to be changed each time the data is loaded into the DataGridView. Add a DataBindingComplete event handler to provide the code that changes the default behavior. To run this example, paste the code into a form that contains a DataGridView named dataGridView1 and ensure that all events are associated with their event handlers.

Private Sub dataGridView1_ColumnHeaderMouseClick(ByVal sender As Object, _
    ByVal e As DataGridViewCellMouseEventArgs) _
    Handles dataGridView1.ColumnHeaderMouseClick

    Dim newColumn As DataGridViewColumn = _
    Dim oldColumn As DataGridViewColumn = dataGridView1.SortedColumn
    Dim direction As ListSortDirection

    ' If oldColumn is null, then the DataGridView is not currently sorted.
    If oldColumn IsNot Nothing Then

        ' Sort the same column again, reversing the SortOrder.
        If oldColumn Is newColumn AndAlso dataGridView1.SortOrder = _
            SortOrder.Ascending Then
            direction = ListSortDirection.Descending

            ' Sort a new column and remove the old SortGlyph.
            direction = ListSortDirection.Ascending
            oldColumn.HeaderCell.SortGlyphDirection = SortOrder.None
        End If
        direction = ListSortDirection.Ascending
    End If

    ' Sort the selected column.
    dataGridView1.Sort(newColumn, direction)
    If direction = ListSortDirection.Ascending Then
        newColumn.HeaderCell.SortGlyphDirection = SortOrder.Ascending
        newColumn.HeaderCell.SortGlyphDirection = SortOrder.Descending
    End If

End Sub

Private Sub dataGridView1_DataBindingComplete(ByVal sender As Object, _
    ByVal e As DataGridViewBindingCompleteEventArgs) _
    Handles dataGridView1.DataBindingComplete

    ' Put each of the columns into programmatic sort mode.
    For Each column As DataGridViewColumn In dataGridView1.Columns
        column.SortMode = DataGridViewColumnSortMode.Programmatic
End Sub

.NET Framework
Available since 2.0
Return to top