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

Комментарии

Это событие возникает только в DataSource том случае, если свойство не задано, а VirtualMode значение свойства равно false.

Это событие сравнивает пары ячеек в сортируемого столбце. Это происходит, только когда пользователь щелкает заголовок столбца со значением SortModeAutomaticсвойства , или при вызове перегрузки Sort(DataGridViewColumn, ListSortDirection) . При возникновении этого события для столбца со значением SortModeProgrammaticсвойства необходимо самостоятельно отобразить глиф сортировки DataGridViewColumnHeaderCell.SortGlyphDirection через свойство .

Это событие можно использовать для сортировки строк по значениям ячеек в одном или нескольких столбцах. CellValue1 Используйте свойства и CellValue2 для сравнения значений ячеек в столбце, указанном в свойстве Column . RowIndex1 Используйте свойства и RowIndex2 для доступа к значениям в других столбцах через коллекциюRows.

Дополнительные сведения об обработке событий см. в разделе Обработка и создание событий.

Применяется к

См. также раздел