Click to Rate and Give Feedback
MSDN
MSDN Library
.NET Development
.NET Framework 3.5
DataGridView Class
Sort Method
 Sort Method (IComparer)
Collapse All/Expand All Collapse All
This page is specific to
Microsoft Visual Studio 2008/.NET Framework 3.5

Other versions are also available for the following:
.NET Framework Class Library
DataGridView..::.Sort Method (IComparer)

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

Namespace:  System.Windows.Forms
Assembly:  System.Windows.Forms (in System.Windows.Forms.dll)
Visual Basic (Declaration)
Public Overridable Sub Sort ( _
    comparer As IComparer _
)
Visual Basic (Usage)
Dim instance As DataGridView
Dim comparer As IComparer

instance.Sort(comparer)
C#
public virtual void Sort(
    IComparer comparer
)
Visual C++
public:
virtual void Sort(
    IComparer^ comparer
)
JScript
public function Sort(
    comparer : IComparer
)

Parameters

comparer
Type: System.Collections..::.IComparer
An implementation of IComparer that performs the custom sorting operation.
ExceptionCondition
ArgumentNullException

comparer is nullNothingnullptra null reference (Nothing in Visual Basic).

InvalidOperationException

VirtualMode is set to true.

-or-

DataSource is not nullNothingnullptra null reference (Nothing in Visual Basic).

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 nullNothingnullptra null reference (Nothing in Visual Basic).

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.

Visual Basic
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
C#
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;
    }
}

Windows 7, Windows Vista, Windows XP SP2, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP Starter Edition, Windows Server 2008 R2, Windows Server 2008, Windows Server 2003, Windows Server 2000 SP4, Windows Millennium Edition, Windows 98

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

.NET Framework

Supported in: 3.5, 3.0, 2.0
Tags What's this?: Add a tag
Community Content   What is Community Content?
Add new content RSS  Annotations
Processing
© 2009 Microsoft Corporation. All rights reserved. Terms of Use | Trademarks | Privacy Statement | Site Feedback
Page view tracker