DataGridView.Sort DataGridView.Sort DataGridView.Sort DataGridView.Sort Method

定义

DataGridView 控件的内容进行排序。Sorts the contents of the DataGridView control.

重载

Sort(IComparer) Sort(IComparer) Sort(IComparer) Sort(IComparer)

使用 IComparer 接口的实现来对 DataGridView 控件的内容进行排序。Sorts the contents of the DataGridView control using an implementation of the IComparer interface.

Sort(DataGridViewColumn, ListSortDirection) Sort(DataGridViewColumn, ListSortDirection) Sort(DataGridViewColumn, ListSortDirection)

基于指定列的内容,按升序或降序对 DataGridView 控件的内容进行排序。Sorts the contents of the DataGridView control in ascending or descending order based on the contents of the specified column.

Sort(IComparer) Sort(IComparer) Sort(IComparer) Sort(IComparer)

使用 IComparer 接口的实现来对 DataGridView 控件的内容进行排序。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)

参数

comparer
IComparer IComparer IComparer IComparer

执行自定义排序操作的 IComparer 的实现。An implementation of IComparer that performs the custom sorting operation.

异常

示例

下面的代码示例演示如何在多列Sort排序方案中使用方法重载。The following code example demonstrates how to use the Sort method overload in a multiple column sort scenario. 在此示例中, IComparer接口是RowComparer在类中实现的。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

注解

此方法允许对DataGridView类的排序功能进行高级自定义。This method allows advanced customization of the sorting feature of the DataGridView class. 为了实现高度自定义的排序操作,可以编写ColumnHeaderMouseClick事件的事件处理程序,并使用System.Collections.IComparer实现接口的类的实例作为参数来调用此方法。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. 在这种情况下,通常会将DataGridViewColumn.SortMode属性设置DataGridViewColumnSortMode.Programmatic为以禁用自动排序,并为排序标志符号留出空间。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. 如果按设置为编程排序模式的列进行排序,则必须通过设置DataGridViewColumnHeaderCell.SortGlyphDirection属性来自行显示排序标志符号。When sorting by columns set to programmatic sort mode, you must display the sorting glyph yourself by setting the DataGridViewColumnHeaderCell.SortGlyphDirection property.

仅当未设置属性时DataSource ,此方法才有效。This method works only when the DataSource property is not set. DataGridView控件绑定到外部数据源时,必须使用该数据源提供的排序操作。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.

调用此方法会将CurrentCell属性自动设置为。 nullCalling this method automatically sets the CurrentCell property to null.

另请参阅

Sort(DataGridViewColumn, ListSortDirection) Sort(DataGridViewColumn, ListSortDirection) Sort(DataGridViewColumn, ListSortDirection)

基于指定列的内容,按升序或降序对 DataGridView 控件的内容进行排序。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

参数

dataGridViewColumn
DataGridViewColumn DataGridViewColumn DataGridViewColumn DataGridViewColumn

DataGridView 的内容进行排序时所依据的列。The column by which to sort the contents of the DataGridView.

异常

指定的列不属于此 DataGridViewThe specified column is not part of this DataGridView.

- 或 --or- DataSource 属性已设置,而指定列的 IsDataBound 属性返回 falseThe DataSource property has been set and the IsDataBound property of the specified column returns false.

dataGridViewColumnnulldataGridViewColumn is null.

VirtualMode 属性设置为 true ,而指定列的 IsDataBound 属性返回 falseThe VirtualMode property is set to true and the IsDataBound property of the specified column returns false.

-or- DataSource 属性指定的对象未实现 IBindingList 接口。The object specified by the DataSource property does not implement the IBindingList interface.

-or- DataSource 属性指定的对象的 SupportsSorting 属性值为 falseThe object specified by the DataSource property has a SupportsSorting property value of false.

示例

下面的代码示例演示如何Sort在编程排序中使用。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

注解

此方法通过比较指定列中DataGridView的值对的内容进行排序。This method sorts the contents of the DataGridView by comparing values in the specified column. 默认情况下,排序操作将使用Compare DataGridViewCell.Value属性来比较列中的单元对。By default, the sort operation will use the Compare method to compare pairs of cells in the column using the DataGridViewCell.Value property.

对于SortMode属性设置为DataGridViewColumnSortMode.Automatic的列, SortedColumnSortOrder属性将自动设置并显示相应的排序标志符号。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. 对于SortMode属性设置为DataGridViewColumnSortMode.Programmatic的列,必须通过DataGridViewColumnHeaderCell.SortGlyphDirection属性自行显示排序标志符号。For columns with the SortMode property set to DataGridViewColumnSortMode.Programmatic, you must display the sorting glyph yourself through the DataGridViewColumnHeaderCell.SortGlyphDirection property.

您可以通过处理SortCompare该事件来自定义此方法使用的排序操作。You can customize the sorting operation used by this method by handling the SortCompare event. 此事件仅在未设置DataSource属性的情况下发生。This event occurs only when the DataSource property has not been set.

DataSource设置属性后,此方法仅适用于数据绑定列。When the DataSource property has been set, this method works for data-bound columns only. 数据绑定列已设置其DataGridViewColumn.DataPropertyName属性。Data-bound columns have had their DataGridViewColumn.DataPropertyName property set. 这将DataGridViewColumn.IsDataBound导致属性返回trueThis causes the DataGridViewColumn.IsDataBound property to return true.

DataGridView如果控件同时包含绑定列和未绑定列,则当控件按绑定列进行排序时,必须实现虚模式来维护未绑定列的值。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. 可以通过将VirtualMode属性设置为true并处理CellValueNeeded事件来执行此操作。You can do this by setting the VirtualMode property to true and handling the CellValueNeeded event. 如果列可编辑,还应处理CellValuePushed事件。If the column is editable, you should also handle the CellValuePushed event. 有关虚拟模式的详细信息,请参阅如何:在 Windows 窗体 DataGridView 控件中实现虚拟模式。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.

另请参阅

适用于