DataGridView.Sort 方法

定義

DataGridView 控制項的內容排序。Sorts the contents of the DataGridView control.

多載

Sort(IComparer)

使用 IComparer 介面的實作,將 DataGridView 控制項的內容排序。Sorts the contents of the DataGridView control using an implementation of the IComparer interface.

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)

使用 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 實作。An implementation of IComparer that performs the custom sorting operation.

例外狀況

comparernullcomparer is null.

VirtualMode 設定為 trueVirtualMode is set to true.

-或--or- DataSource 不是 nullDataSource is not null.

範例

下列程式碼範例示範如何 Sort 在多個資料行排序案例中使用方法多載。The following code example demonstrates how to use the Sort method overload in a multiple column sort scenario. 在此範例中, IComparer 會在類別中實作為介面 RowComparerIn 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

備註

這個方法可讓您自訂類別之排序功能的自訂 DataGridViewThis method allows advanced customization of the sorting feature of the DataGridView class. 若要執行高度自訂的排序作業,您可以撰寫事件的事件處理常式, ColumnHeaderMouseClick 並使用將介面實作為參數的類別實例來呼叫此方法 System.Collections.IComparerIn 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.SortGlyphDirectionWhen 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)

根據指定資料行的內容,以遞增或遞減順序將 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
Public Overridable Sub Sort (dataGridViewColumn As DataGridViewColumn, direction As ListSortDirection)

參數

dataGridViewColumn
DataGridViewColumn

DataGridView 內容排序時,所依據的資料行。The column by which to sort the contents of the DataGridView.

direction
ListSortDirection

其中一個 ListSortDirection 值。One of the ListSortDirection values.

例外狀況

指定的資料行不屬於這個 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 屬性所指定的物件具有 falseSupportsSorting 屬性值。The object specified by the DataSource property has a SupportsSorting property value of false.

範例

下列程式碼範例示範如何以程式設計的方式來使用 SortThe 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.ValueBy 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.SortGlyphDirectionFor columns with the SortMode property set to DataGridViewColumnSortMode.Programmatic, you must display the sorting glyph yourself through the DataGridViewColumnHeaderCell.SortGlyphDirection property.

您可以藉由處理事件來自訂此方法所使用的排序作業 SortCompareYou can customize the sorting operation used by this method by handling the SortCompare event. 只有在尚未設定屬性時,才會發生此事件 DataSourceThis 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. 您可以藉由將屬性設定 VirtualModetrue 和處理事件來完成這項作業 CellValueNeededYou 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 Forms 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.

適用於