DataGridView.Sort Method

Definition

Sorts the contents of the DataGridView control.

Overloads

Sort(IComparer)

Sorts the contents of the DataGridView control using an implementation of the IComparer interface.

Sort(DataGridViewColumn, ListSortDirection)

Sorts the contents of the DataGridView control in ascending or descending order based on the contents of the specified column.

Sort(IComparer)

Sorts the contents of the DataGridView control using an implementation of the IComparer interface.

public:
 virtual void Sort(System::Collections::IComparer ^ comparer);
public virtual void Sort (System.Collections.IComparer comparer);
abstract member Sort : System.Collections.IComparer -> unit
override this.Sort : System.Collections.IComparer -> unit
Public Overridable Sub Sort (comparer As IComparer)

Parameters

comparer
IComparer

An implementation of IComparer that performs the custom sorting operation.

Exceptions

comparer is null.

VirtualMode is set to true.

-or-

DataSource is not null.

Examples

The following code example demonstrates how to use the Sort method overload in a multiple column sort scenario. In this example, the IComparer interface is implemented in the RowComparer class.

private void Button1_Click( object sender, EventArgs e )
{
    if ( RadioButton1.Checked == true )
    {
        DataGridView1.Sort( new RowComparer( SortOrder.Ascending ) );
    }
    else if ( RadioButton2.Checked == true )
    {
        DataGridView1.Sort( new RowComparer( SortOrder.Descending ) );
    }
}

private class RowComparer : System.Collections.IComparer
{
    private static int sortOrderModifier = 1;

    public RowComparer(SortOrder sortOrder)
    {
        if (sortOrder == SortOrder.Descending)
        {
            sortOrderModifier = -1;
        }
        else if (sortOrder == SortOrder.Ascending)
        {
            sortOrderModifier = 1;
        }
    }

    public int Compare(object x, object y)
    {
        DataGridViewRow DataGridViewRow1 = (DataGridViewRow)x;
        DataGridViewRow DataGridViewRow2 = (DataGridViewRow)y;

        // Try to sort based on the Last Name column.
        int CompareResult = System.String.Compare(
            DataGridViewRow1.Cells[1].Value.ToString(),
            DataGridViewRow2.Cells[1].Value.ToString());

        // If the Last Names are equal, sort based on the First Name.
        if ( CompareResult == 0 )
        {
            CompareResult = System.String.Compare(
                DataGridViewRow1.Cells[0].Value.ToString(),
                DataGridViewRow2.Cells[0].Value.ToString());
        }
        return CompareResult * sortOrderModifier;
    }
}
Private Sub Button1_Click(ByVal sender As Object, ByVal e As EventArgs) _
Handles Button1.Click
    If RadioButton1.Checked = True Then
        DataGridView1.Sort(New RowComparer(SortOrder.Ascending))
    ElseIf RadioButton2.Checked = True Then
        DataGridView1.Sort(New RowComparer(SortOrder.Descending))
    End If
End Sub

Private Class RowComparer
    Implements System.Collections.IComparer

    Private sortOrderModifier As Integer = 1

    Public Sub New(ByVal sortOrder As SortOrder)
        If sortOrder = sortOrder.Descending Then
            sortOrderModifier = -1
        ElseIf sortOrder = sortOrder.Ascending Then

            sortOrderModifier = 1
        End If
    End Sub

    Public Function Compare(ByVal x As Object, ByVal y As Object) As Integer _
        Implements System.Collections.IComparer.Compare

        Dim DataGridViewRow1 As DataGridViewRow = CType(x, DataGridViewRow)
        Dim DataGridViewRow2 As DataGridViewRow = CType(y, DataGridViewRow)

        ' Try to sort based on the Last Name column.
        Dim CompareResult As Integer = System.String.Compare( _
            DataGridViewRow1.Cells(1).Value.ToString(), _
            DataGridViewRow2.Cells(1).Value.ToString())

        ' If the Last Names are equal, sort based on the First Name.
        If CompareResult = 0 Then
            CompareResult = System.String.Compare( _
                DataGridViewRow1.Cells(0).Value.ToString(), _
                DataGridViewRow2.Cells(0).Value.ToString())
        End If
        Return CompareResult * sortOrderModifier
    End Function
End Class

Remarks

This method allows advanced customization of the sorting feature of the DataGridView class. In order to implement a highly customized sorting operation, you can write an event handler for the ColumnHeaderMouseClick event and call this method with an instance of a class that implements the System.Collections.IComparer interface as a parameter. In this case, you will typically set the DataGridViewColumn.SortMode property to DataGridViewColumnSortMode.Programmatic to disable automatic sorting and to leave room for a sorting glyph. When sorting by columns set to programmatic sort mode, you must display the sorting glyph yourself by setting the DataGridViewColumnHeaderCell.SortGlyphDirection property.

This method works only when the DataSource property is not set. When you bind the DataGridView control to an external data source, you must use the sorting operations provided by that data source. When you provide your own data source by implementing virtual mode, you must also handle the sorting operations yourself.

Calling this method automatically sets the CurrentCell property to null.

See also

Applies to

Sort(DataGridViewColumn, ListSortDirection)

Sorts the contents of the DataGridView control in ascending or descending order based on the contents of the specified column.

public:
 virtual void Sort(System::Windows::Forms::DataGridViewColumn ^ dataGridViewColumn, System::ComponentModel::ListSortDirection direction);
public virtual void Sort (System.Windows.Forms.DataGridViewColumn dataGridViewColumn, System.ComponentModel.ListSortDirection direction);
abstract member Sort : System.Windows.Forms.DataGridViewColumn * System.ComponentModel.ListSortDirection -> unit
override this.Sort : System.Windows.Forms.DataGridViewColumn * System.ComponentModel.ListSortDirection -> unit
Public Overridable Sub Sort (dataGridViewColumn As DataGridViewColumn, direction As ListSortDirection)

Parameters

dataGridViewColumn
DataGridViewColumn

The column by which to sort the contents of the DataGridView.

direction
ListSortDirection

One of the ListSortDirection values.

Exceptions

The specified column is not part of this DataGridView.

-or-

The DataSource property has been set and the IsDataBound property of the specified column returns false.

dataGridViewColumn is null.

The VirtualMode property is set to true and the IsDataBound property of the specified column returns false.

-or-

The object specified by the DataSource property does not implement the IBindingList interface.

-or-

The object specified by the DataSource property has a SupportsSorting property value of false.

Examples

The following code example demonstrates how to use the Sort in a programmatic sort.

private void sortButton_Click(object sender, System.EventArgs e)
{
    // Check which column is selected, otherwise set NewColumn to null.
    DataGridViewColumn newColumn =
        dataGridView1.Columns.GetColumnCount(
        DataGridViewElementStates.Selected) == 1 ?
        dataGridView1.SelectedColumns[0] : null;

    DataGridViewColumn oldColumn = dataGridView1.SortedColumn;
    ListSortDirection direction;

    // If oldColumn is null, then the DataGridView is not currently sorted.
    if (oldColumn != null)
    {
        // Sort the same column again, reversing the SortOrder.
        if (oldColumn == newColumn &&
            dataGridView1.SortOrder == SortOrder.Ascending)
        {
            direction = ListSortDirection.Descending;
        }
        else
        {
            // Sort a new column and remove the old SortGlyph.
            direction = ListSortDirection.Ascending;
            oldColumn.HeaderCell.SortGlyphDirection = SortOrder.None;
        }
    }
    else
    {
        direction = ListSortDirection.Ascending;
    }

    // If no column has been selected, display an error dialog  box.
    if (newColumn == null)
    {
        MessageBox.Show("Select a single column and try again.",
            "Error: Invalid Selection", MessageBoxButtons.OK,
            MessageBoxIcon.Error);
    }
    else
    {
        dataGridView1.Sort(newColumn, direction);
        newColumn.HeaderCell.SortGlyphDirection =
            direction == ListSortDirection.Ascending ?
            SortOrder.Ascending : SortOrder.Descending;
    }
}
Private Sub SortButton_Click(ByVal sender As Object, _
    ByVal e As EventArgs) Handles sortButton.Click

    ' Check which column is selected, otherwise set NewColumn to Nothing.
    Dim newColumn As DataGridViewColumn
    If dataGridView1.Columns.GetColumnCount(DataGridViewElementStates _
        .Selected) = 1 Then
        newColumn = dataGridView1.SelectedColumns(0)
    Else
        newColumn = Nothing
    End If

    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
        Else

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


    ' If no column has been selected, display an error dialog  box.
    If newColumn Is Nothing Then
        MessageBox.Show("Select a single column and try again.", _
            "Error: Invalid Selection", MessageBoxButtons.OK, _
            MessageBoxIcon.Error)
    Else
        dataGridView1.Sort(newColumn, direction)
        If direction = ListSortDirection.Ascending Then
            newColumn.HeaderCell.SortGlyphDirection = SortOrder.Ascending
        Else
            newColumn.HeaderCell.SortGlyphDirection = SortOrder.Descending
        End If
    End If

End Sub

Remarks

This method sorts the contents of the DataGridView by comparing values in the specified column. By default, the sort operation will use the Compare method to compare pairs of cells in the column using the DataGridViewCell.Value property.

For columns with the SortMode property set to DataGridViewColumnSortMode.Automatic, the SortedColumn and SortOrder properties are set automatically and the appropriate sorting glyph is displayed. For columns with the SortMode property set to DataGridViewColumnSortMode.Programmatic, you must display the sorting glyph yourself through the DataGridViewColumnHeaderCell.SortGlyphDirection property.

You can customize the sorting operation used by this method by handling the SortCompare event. This event occurs only when the DataSource property has not been set.

When the DataSource property has been set, this method works for data-bound columns only. Data-bound columns have had their DataGridViewColumn.DataPropertyName property set. This causes the DataGridViewColumn.IsDataBound property to return true.

If your DataGridView control contains both bound and unbound columns, you must implement virtual mode to maintain the values of the unbound columns when the control is sorted by a bound column. You can do this by setting the VirtualMode property to true and handling the CellValueNeeded event. If the column is editable, you should also handle the CellValuePushed event. For more information about virtual mode, see How to: Implement Virtual Mode in the Windows Forms DataGridView Control. Sorting by unbound columns when the control is data-bound is not supported.

See also

Applies to