DataGridView.SortCompare イベント

定義

DataGridView が並べ替え操作を実行するために 2 つのセルの値を比較する場合に発生します。

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場合にのみ発生します。

このイベントは、並べ替えられている列のセルのペアを比較します。 これは、ユーザーが プロパティ値 Automaticが の列SortModeのヘッダーをクリックしたとき、またはオーバーロードを呼び出すときにのみ発生しますSort(DataGridViewColumn, ListSortDirection)。 プロパティ値 が のProgrammatic列にSortMode対してこのイベントが発生した場合は、 プロパティを使用して並べ替えグリフを自分で表示するDataGridViewColumnHeaderCell.SortGlyphDirection必要があります。

このイベントを使用すると、1 つの列または複数の列のセル値を使用して行を並べ替えることができます。 プロパティで CellValue1 指定された列のセル値を比較するには、 プロパティと CellValue2 プロパティを Column 使用します。 プロパティと RowIndex2 プロパティをRowIndex1使用して、コレクションを介して他の列の値にRowsアクセスします。

イベントを処理する方法の詳細については、次を参照してください。処理とイベントの発生します。

適用対象

こちらもご覧ください