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. 在此範例中,@no__t 0 介面會在 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 事件的事件處理常式,並使用實作為參數的類別 @no__t 的實例來呼叫此方法。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)

根據指定資料行的內容,以遞增或遞減順序將 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

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.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 的資料行,系統會自動設定 SortedColumn 和 @no__t 3 屬性,並顯示適當的排序圖像。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.

如果您的 @no__t 0 控制項同時包含系結和未系結的資料行,則當控制項由系結資料行排序時,您必須執行虛擬模式來維護未系結之資料行的值。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. 如需虛擬模式的詳細資訊,請參閱 [How to:在 Windows Forms DataGridView 控制項 @ no__t-0 中執行虛擬模式。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.

另請參閱

適用於