Export (0) Print
Expand All
Expand Minimize

DataGridView.SortCompare Event

Occurs when the DataGridView compares two cell values to perform a sort operation.

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

'Declaration
Public Event SortCompare As DataGridViewSortCompareEventHandler

This event occurs only when the DataSource property is not set and the VirtualMode property value is false.

This event compares pairs of cells in the column being sorted. It occurs only when the user clicks the header of a column with a SortMode property value of Automatic, or when you call the Sort(DataGridViewColumn, ListSortDirection) overload. When this event occurs for a column with a SortMode property value of Programmatic, you must display the sorting glyph yourself through the DataGridViewColumnHeaderCell.SortGlyphDirection property.

You can use this event to sort rows using the cell values in one column or in multiple columns. Use the CellValue1 and CellValue2 properties to compare cell values in the column specified in the Column property. Use the RowIndex1 and RowIndex2 properties to access values in other columns through the Rows collection.

For more information about handling events, see Consuming Events.

The following code example demonstrates how to use the SortCompare in a multiple column sort. This example is part of a larger example provided in How to: Customize Sorting in the Windows Forms DataGridView Control.

Private Sub DataGridView1_SortCompare( _
    ByVal sender As Object, ByVal e As DataGridViewSortCompareEventArgs) _
    Handles DataGridView1.SortCompare

    ' Try to sort based on the contents of the cell in the current column.
    e.SortResult = System.String.Compare(e.CellValue1.ToString(), _
        e.CellValue2.ToString())

    ' If the cells are equal, sort based on the ID column. 
    If (e.SortResult = 0) AndAlso Not (e.Column.Name = "ID") Then
        e.SortResult = System.String.Compare( _
            DataGridView1.Rows(e.RowIndex1).Cells("ID").Value.ToString(), _
            DataGridView1.Rows(e.RowIndex2).Cells("ID").Value.ToString())
    End If

    e.Handled = True 

End Sub

.NET Framework

Supported in: 4.6, 4.5, 4, 3.5, 3.0, 2.0

.NET Framework Client Profile

Supported in: 4, 3.5 SP1

Windows 8.1, Windows Server 2012 R2, Windows 8, Windows Server 2012, Windows 7, Windows Vista SP2, Windows Server 2008 (Server Core Role not supported), Windows Server 2008 R2 (Server Core Role supported with SP1 or later; Itanium not supported)

The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.

Show:
© 2014 Microsoft