- How to: Customize Sorting in the Windows Forms DataGridView Control
- Programmatic Sorting
- Custom Sorting Using the SortCompare Event
- Custom Sorting Using the IComparer Interface
- Data Grid View. Sort Метод
- Определение
- Перегрузки
- Sort(IComparer)
- Параметры
- Исключения
- Примеры
- Комментарии
- Применяется к
- Sort(DataGridViewColumn, ListSortDirection)
- Параметры
- Исключения
- Примеры
- Комментарии
- Column Sort Modes in the Windows Forms DataGridView Control
- Programmatic Sorting
- Custom Sorting
How to: Customize Sorting in the Windows Forms DataGridView Control
The DataGridView control provides automatic sorting but, depending on your needs, you might need to customize sort operations. For example, you can use programmatic sorting to create an alternate user interface (UI). Alternatively, you can handle the SortCompare event or call the Sort(IComparer) overload of the Sort method for greater sorting flexibility, such as sorting multiple columns.
The following code examples demonstrate these three approaches to custom sorting. For more information, see Column Sort Modes in the Windows Forms DataGridView Control.
Programmatic Sorting
The following code example demonstrates a programmatic sort using the SortOrder and SortedColumn properties to determine the direction of the sort, and the SortGlyphDirection property to manually set the sort glyph. The Sort(DataGridViewColumn,ListSortDirection) overload of the Sort method is used to sort data only in a single column.
Custom Sorting Using the SortCompare Event
The following code example demonstrates custom sorting using a SortCompare event handler. The selected DataGridViewColumn is sorted and, if there are duplicate values in the column, the ID column is used to determine the final order.
Custom Sorting Using the IComparer Interface
The following code example demonstrates custom sorting using the Sort(IComparer) overload of the Sort method, which takes an implementation of the IComparer interface to perform a multiple-column sort.
Data Grid View. Sort Метод
Определение
Сортирует содержимое элемента управления DataGridView. Sorts the contents of the DataGridView control.
Перегрузки
Сортирует содержимое элемента управления DataGridView, используя реализацию интерфейса IComparer. Sorts the contents of the DataGridView control using an implementation of the IComparer interface.
Сортирует содержимое элемента управления DataGridView по убыванию или по возрастанию, основываясь на содержимом указанного столбца. Sorts the contents of the DataGridView control in ascending or descending order based on the contents of the specified column.
Sort(IComparer)
Сортирует содержимое элемента управления DataGridView, используя реализацию интерфейса IComparer. Sorts the contents of the DataGridView control using an implementation of the IComparer interface.
Параметры
Реализация объекта IComparer, выполняющего операцию пользовательской сортировки. An implementation of IComparer that performs the custom sorting operation.
Исключения
comparer имеет значение null . comparer is null .
Параметру VirtualMode задается значение true . VirtualMode is set to true .
-или- -or- DataSource не является null . DataSource is not null .
Примеры
В следующем примере кода показано, как использовать Sort перегрузку метода в сценарии сортировки с несколькими столбцами. The following code example demonstrates how to use the Sort method overload in a multiple column sort scenario. В этом примере IComparer интерфейс реализован в RowComparer классе. In this example, the IComparer interface is implemented in the RowComparer class.
Комментарии
Этот метод обеспечивает расширенную настройку функции сортировки DataGridView класса. This method allows advanced customization of the sorting feature of the DataGridView class. Для реализации строго настраиваемой операции сортировки можно написать обработчик событий для ColumnHeaderMouseClick события и вызвать этот метод с экземпляром класса, реализующего System.Collections.IComparer интерфейс в качестве параметра. In order to implement a highly customized sorting operation, you can write an event handler for the ColumnHeaderMouseClick event and call this method with an instance of a class that implements the System.Collections.IComparer interface as a parameter. В этом случае свойству обычно присвоено значение, чтобы DataGridViewColumn.SortMode DataGridViewColumnSortMode.Programmatic Отключить автоматическую сортировку и оставить место для глифа сортировки. In this case, you will typically set the DataGridViewColumn.SortMode property to DataGridViewColumnSortMode.Programmatic to disable automatic sorting and to leave room for a sorting glyph. При сортировке по столбцам, установленным в режим программной сортировки, необходимо самостоятельно отобразить глиф сортировки, задав DataGridViewColumnHeaderCell.SortGlyphDirection свойство. When sorting by columns set to programmatic sort mode, you must display the sorting glyph yourself by setting the DataGridViewColumnHeaderCell.SortGlyphDirection property.
Этот метод работает, только если DataSource свойство не задано. This method works only when the DataSource property is not set. При привязке DataGridView элемента управления к внешнему источнику данных необходимо использовать операции сортировки, предоставляемые этим источником данных. When you bind the DataGridView control to an external data source, you must use the sorting operations provided by that data source. При предоставлении собственного источника данных путем реализации виртуального режима необходимо также выполнять операции сортировки самостоятельно. When you provide your own data source by implementing virtual mode, you must also handle the sorting operations yourself.
При вызове этого метода свойству автоматически присваивается значение CurrentCell null . Calling this method automatically sets the CurrentCell property to null .
Применяется к
Sort(DataGridViewColumn, ListSortDirection)
Сортирует содержимое элемента управления DataGridView по убыванию или по возрастанию, основываясь на содержимом указанного столбца. Sorts the contents of the DataGridView control in ascending or descending order based on the contents of the specified column.
Параметры
Столбец, по которому выполняется сортировка содержимого DataGridView. The column by which to sort the contents of the DataGridView.
Одно из значений перечисления ListSortDirection. One of the ListSortDirection values.
Исключения
Указанный столбец не является частью этого DataGridView. The specified column is not part of this DataGridView.
-или- -or- Свойство DataSource задано, и свойство IsDataBound указанного столбца возвращает false . The DataSource property has been set and the IsDataBound property of the specified column returns false .
dataGridViewColumn имеет значение null . dataGridViewColumn is null .
Для свойства VirtualMode задано значение true , и свойство IsDataBound указанного столбца возвращает false . The VirtualMode property is set to true and the IsDataBound property of the specified column returns false .
-или- -or- Объект, указанный свойством DataSource, не реализует интерфейс IBindingList. The object specified by the DataSource property does not implement the IBindingList interface.
-или- -or- Объект, указанный свойством DataSource, имеет значение свойства SupportsSorting, равное false . The object specified by the DataSource property has a SupportsSorting property value of false .
Примеры
В следующем примере кода показано, как использовать Sort в программной сортировке. The following code example demonstrates how to use the Sort in a programmatic sort.
Комментарии
Этот метод сортирует содержимое объекта DataGridView путем сравнения значений в указанном столбце. This method sorts the contents of the DataGridView by comparing values in the specified column. По умолчанию операция сортировки будет использовать Compare метод для сравнения пар ячеек в столбце с помощью DataGridViewCell.Value Свойства. By default, the sort operation will use the Compare method to compare pairs of cells in the column using the DataGridViewCell.Value property.
Для столбцов, для которых SortMode свойство имеет значение DataGridViewColumnSortMode.Automatic , SortedColumn SortOrder Свойства и задаются автоматически и отображается соответствующий глиф сортировки. For columns with the SortMode property set to DataGridViewColumnSortMode.Automatic, the SortedColumn and SortOrder properties are set automatically and the appropriate sorting glyph is displayed. Для столбцов со SortMode свойством, для которых задано значение DataGridViewColumnSortMode.Programmatic , необходимо самостоятельно отобразить глиф сортировки с помощью DataGridViewColumnHeaderCell.SortGlyphDirection Свойства. For columns with the SortMode property set to DataGridViewColumnSortMode.Programmatic, you must display the sorting glyph yourself through the DataGridViewColumnHeaderCell.SortGlyphDirection property.
Вы можете настроить операцию сортировки, используемую этим методом, обрабатывая SortCompare событие. You can customize the sorting operation used by this method by handling the SortCompare event. Это событие возникает только в том случае, если DataSource свойство не было задано. This event occurs only when the DataSource property has not been set.
Если DataSource свойство задано, этот метод работает только для столбцов с привязкой к данным. When the DataSource property has been set, this method works for data-bound columns only. Для столбцов с привязкой к данным DataGridViewColumn.DataPropertyName заданы свойства. Data-bound columns have had their DataGridViewColumn.DataPropertyName property set. Это приводит к DataGridViewColumn.IsDataBound возврату свойства true . This causes the DataGridViewColumn.IsDataBound property to return true .
Если DataGridView элемент управления содержит как связанные, так и несвязанные столбцы, необходимо реализовать виртуальный режим для сохранения значений непривязанных столбцов, когда элемент управления сортируется по связанному столбцу. If your DataGridView control contains both bound and unbound columns, you must implement virtual mode to maintain the values of the unbound columns when the control is sorted by a bound column. Это можно сделать, задав VirtualMode для свойства значение true и обрабатывая CellValueNeeded событие. You can do this by setting the VirtualMode property to true and handling the CellValueNeeded event. Если столбец доступен для редактирования, необходимо также выполнить обработку CellValuePushed события. If the column is editable, you should also handle the CellValuePushed event. Дополнительные сведения о виртуальном режиме см. в разделе инструкции. Реализация виртуального режима в элементе управления Windows Forms DataGridView. For more information about virtual mode, see How to: Implement Virtual Mode in the Windows Forms DataGridView Control. Сортировка по несвязанным столбцам, если элемент управления привязан к данным, не поддерживается. Sorting by unbound columns when the control is data-bound is not supported.
Column Sort Modes in the Windows Forms DataGridView Control
DataGridView columns have three sort modes. The sort mode for each column is specified through the SortMode property of the column, which can be set to one of the following DataGridViewColumnSortMode enumeration values.
DataGridViewColumnSortMode value | Description |
---|---|
Automatic | Default for text box columns. Unless column headers are used for selection, clicking the column header automatically sorts the DataGridView by this column and displays a glyph indicating the sort order. |
NotSortable | Default for non–text box columns. You can sort this column programmatically; however, it is not intended for sorting, so no space is reserved for the sorting glyph. |
Programmatic | You can sort this column programmatically, and space is reserved for the sorting glyph. |
You might want to change the sort mode for a column that defaults to NotSortable if it contains values that can be meaningfully ordered. For example, if you have a database column containing numbers that represent item states, you can display these numbers as corresponding icons by binding an image column to the database column. You can then change the numerical cell values into image display values in a handler for the DataGridView.CellFormatting event. In this case, setting the SortMode property to Automatic will enable your users to sort the column. Automatic sorting will enable your users to group items that have the same state even if the states corresponding to the numbers do not have a natural sequence. Check box columns are another example where automatic sorting is useful for grouping items in the same state.
You can sort a DataGridView programmatically by the values in any column or in multiple columns, regardless of the SortMode settings. Programmatic sorting is useful when you want to provide your own user interface (UI) for sorting or when you want to implement custom sorting. Providing your own sorting UI is useful, for example, when you set the DataGridView selection mode to enable column header selection. In this case, although the column headers cannot be used for sorting, you still want the headers to display the appropriate sorting glyph, so you would set the SortMode property to Programmatic.
Columns set to programmatic sort mode do not automatically display a sorting glyph. For these columns, you must display the glyph yourself by setting the DataGridViewColumnHeaderCell.SortGlyphDirection property. This is necessary if you want flexibility in custom sorting. For example, if you sort the DataGridView by multiple columns, you might want to display multiple sorting glyphs or no sorting glyph.
Although you can programmatically sort a DataGridView by any column, some columns, such as button columns, might not contain values that can be meaningfully ordered. For these columns, a SortMode property setting of NotSortable indicates that it will never be used for sorting, so there is no need to reserve space in the header for the sorting glyph.
When a DataGridView is sorted, you can determine both the sort column and the sort order by checking the values of the SortedColumn and SortOrder properties. These values are not meaningful after a custom sorting operation. For more information about custom sorting, see the Custom Sorting section later in this topic.
When a DataGridView control containing both bound and unbound columns is sorted, the values in the unbound columns cannot be maintained automatically. To maintain these values, you must implement virtual mode by setting the VirtualMode property to true and handling the CellValueNeeded and CellValuePushed events. For more information, see How to: Implement Virtual Mode in the Windows Forms DataGridView Control. Sorting by unbound columns in bound mode is not supported.
Programmatic Sorting
You can sort a DataGridView programmatically by calling its Sort method.
The Sort(DataGridViewColumn,ListSortDirection) overload of the Sort method takes a DataGridViewColumn and a ListSortDirection enumeration value as parameters. This overload is useful when sorting by columns with values that can be meaningfully ordered, but which you do not want to configure for automatic sorting. When you call this overload and pass in a column with a SortMode property value of DataGridViewColumnSortMode.Automatic, the SortedColumn and SortOrder properties are set automatically and the appropriate sorting glyph appears in the column header.
When the DataGridView control is bound to an external data source by setting the DataSource property, the Sort(DataGridViewColumn,ListSortDirection) method overload does not work for unbound columns. Additionally, when the VirtualMode property is true , you can call this overload only for bound columns. To determine whether a column is data-bound, check the IsDataBound property value. Sorting unbound columns in bound mode is not supported.
Custom Sorting
You can customize DataGridView by using the Sort(IComparer) overload of the Sort method or by handling the SortCompare event.
The Sort(IComparer) method overload takes an instance of a class that implements the IComparer interface as a parameter. This overload is useful when you want to provide custom sorting; for example, when the values in a column do not have a natural sort order or when the natural sort order is inappropriate. In this case, you cannot use automatic sorting, but you might still want your users to sort by clicking the column headers. You can call this overload in a handler for the ColumnHeaderMouseClick event if you do not use column headers for selection.
The Sort(IComparer) method overload works only when the DataGridView control is not bound to an external data source and the VirtualMode property value is false . To customize sorting for columns bound to an external data source, you must use the sorting operations provided by the data source. In virtual mode, you must provide your own sorting operations for unbound columns.
To use the Sort(IComparer) method overload, you must create your own class that implements the IComparer interface. This interface requires your class to implement the IComparer.Compare method, to which the DataGridView passes DataGridViewRow objects as input when the Sort(IComparer) method overload is called. With this, you can calculate the correct row ordering based on the values in any column.
The Sort(IComparer) method overload does not set the SortedColumn and SortOrder properties, so you must always set the DataGridViewColumnHeaderCell.SortGlyphDirection property to display the sorting glyph.
As an alternative to the Sort(IComparer) method overload, you can provide custom sorting by implementing a handler for the SortCompare event. This event occurs when users click the headers of columns configured for automatic sorting or when you call the Sort(DataGridViewColumn,ListSortDirection) overload of the Sort method. The event occurs for each pair of rows in the control, enabling you to calculate their correct order.
The SortCompare event does not occur when the DataSource property is set or when the VirtualMode property value is true .