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されている場合にのみ発生します。

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

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

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

適用対象

こちらもご覧ください