共用方式為


DataGridView.SortCompare 事件

定義

當比較 DataGridView 兩個儲存格值以執行排序操作時,會發生這種情況。

public:
 event System::Windows::Forms::DataGridViewSortCompareEventHandler ^ SortCompare;
public event System.Windows.Forms.DataGridViewSortCompareEventHandler SortCompare;
public event System.Windows.Forms.DataGridViewSortCompareEventHandler? SortCompare;
member this.SortCompare : System.Windows.Forms.DataGridViewSortCompareEventHandler 
Public Custom Event SortCompare As DataGridViewSortCompareEventHandler 

事件類型

範例

以下程式碼範例示範如何在多欄排序中使用 。SortCompare 此範例是《 如何:在 Windows 表單 DataGridView 控制項中自訂排序》中提供較大範例的一部分。

private void dataGridView1_SortCompare(object sender,
    DataGridViewSortCompareEventArgs e)
{
    // Try to sort based on the cells in the current column.
    e.SortResult = System.String.Compare(
        e.CellValue1.ToString(), e.CellValue2.ToString());

    // If the cells are equal, sort based on the ID column.
    if (e.SortResult == 0 && e.Column.Name != "ID")
    {
        e.SortResult = System.String.Compare(
            dataGridView1.Rows[e.RowIndex1].Cells["ID"].Value.ToString(),
            dataGridView1.Rows[e.RowIndex2].Cells["ID"].Value.ToString());
    }
    e.Handled = true;
}
Private Sub DataGridView1_SortCompare( _
    ByVal sender As Object, ByVal e As DataGridViewSortCompareEventArgs) _
    Handles DataGridView1.SortCompare

    ' Try to sort based on the contents of the cell in the current column.
    e.SortResult = System.String.Compare(e.CellValue1.ToString(), _
        e.CellValue2.ToString())

    ' If the cells are equal, sort based on the ID column.
    If (e.SortResult = 0) AndAlso Not (e.Column.Name = "ID") Then
        e.SortResult = System.String.Compare( _
            DataGridView1.Rows(e.RowIndex1).Cells("ID").Value.ToString(), _
            DataGridView1.Rows(e.RowIndex2).Cells("ID").Value.ToString())
    End If

    e.Handled = True

End Sub

備註

此事件僅發生在 DataSource 屬性未設定且 VirtualMode 屬性值為 false時。

此事件比較被排序欄位中的格子對。 它僅在使用者點擊屬性 SortMode 值為 Automatic的欄位標頭,或你呼叫 Sort(DataGridViewColumn, ListSortDirection) 過載時發生。 當屬性值為 Programmatic的欄位SortMode發生此事件時,你必須自己在屬性DataGridViewColumnHeaderCell.SortGlyphDirection中顯示排序字形。

你可以用這個事件來用單欄或多欄的儲存格值來排序列。 使用 CellValue1 and CellValue2 屬性來比較屬性中 Column 指定的欄位中儲存格值。 使用 RowIndex1 and RowIndex2 屬性來存取集合中 Rows 其他欄位的值。

欲了解更多如何處理事件的資訊,請參閱 「處理與提升事件」。

適用於

另請參閱