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 。 此範例是How to: Customize Sorting in the Windows Forms DataGridView Control中提供之較大範例的一部分。

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

備註

只有在未設定 屬性且屬性值為 falseDataSource ,才會 VirtualMode 發生這個事件。

此事件會比較要排序之資料行中的一對儲存格。 只有在使用者按一下屬性值 AutomaticSortMode 的資料行標頭,或呼叫多載時, Sort(DataGridViewColumn, ListSortDirection) 才會發生此情況。 當具有 屬性值 Programmatic 的資料行發生 SortMode 這個事件時,您必須透過 DataGridViewColumnHeaderCell.SortGlyphDirection 屬性自行顯示排序字元。

您可以使用這個事件,使用一個資料行或多個資料行中的資料格值來排序資料列。 CellValue1使用 和 CellValue2 屬性來比較 屬性中所 Column 指定資料行中的資料格值。 RowIndex1使用 和 RowIndex2 屬性,透過 Rows 集合存取其他資料行中的值。

如需如何處理事件的詳細資訊,請參閱 處理和引發事件

適用於

另請參閱