- Сортировка данных в элементе управления Windows Forms DataGridView Sorting data in the Windows Forms DataGridView control
- В этом разделе In this section
- Справочник Reference
- Практическое руководство. Настройка сортировки данных элемента управления DataGridView в Windows Forms How to: Customize Sorting in the Windows Forms DataGridView Control
- Программная сортировка Programmatic Sorting
- Пользовательская сортировка с помощью события SortCompare Custom Sorting Using the SortCompare Event
- Пользовательская сортировка с помощью интерфейса IComparer Custom Sorting Using the IComparer Interface
- Компиляция кода Compiling the Code
- Фильтрация и сортировка данных в приложении Windows Forms Filter and sort data in a Windows Forms application
- Фильтрация данных с помощью компонента BindingSource To filter data by using a BindingSource component
- Сортировка данных с помощью компонента BindingSource To sort data by using a BindingSource component
- List Box. Sorted Свойство
- Определение
- Значение свойства
- Примеры
- Комментарии
- Установка режимов сортировки для столбцов элемента управления DataGridView в Windows Forms Column Sort Modes in the Windows Forms DataGridView Control
- Программная сортировка Programmatic Sorting
- Пользовательская сортировка Custom Sorting
Сортировка данных в элементе управления Windows Forms DataGridView Sorting data in the Windows Forms DataGridView control
По умолчанию пользователи могут сортировать данные в DataGridView элементе управления, щелкая заголовок столбца текстового поля (или нажав клавишу F3, когда ячейка текстового поля сосредоточена на .NET Framework 4.7.2 и более поздних версиях). By default, users can sort the data in a DataGridView control by clicking the header of a text box column (or by pressing F3 when a text box cell is focused on .NET Framework 4.7.2 and later versions). Можно изменить SortMode свойство конкретных столбцов, чтобы разрешить пользователям сортировать по другим типам столбцов, если это имеет смысл. You can modify the SortMode property of specific columns to allow users to sort by other column types when it makes sense to do so. Можно также выполнять сортировку данных программным способом по любому столбцу или по нескольким столбцам. You can also sort the data programmatically by any column, or by multiple columns.
В этом разделе In this section
Практическое руководство. Определение режимов сортировки для столбцов элемента управления DataGridView в Windows Forms How to: Set the Sort Modes for Columns in the Windows Forms DataGridView Control
Описывает, как разрешить пользователям сортировать по столбцам, которые не поддерживают сортировку по умолчанию. Describes how to enable users to sort by columns that are not sortable by default.
Практическое руководство. Настройка сортировки данных элемента управления DataGridView в Windows Forms How to: Customize Sorting in the Windows Forms DataGridView Control
Описывает, как программно сортировать данные и как настраивать сортировку с помощью DataGridView.SortCompare события или путем реализации IComparer интерфейса. Describes how to sort data programmatically and how to customize sorting by using the DataGridView.SortCompare event or by implementing the IComparer interface.
Справочник Reference
DataGridView
Справочная документация по элементу управления DataGridView. Provides reference documentation for the DataGridView control.
DataGridView.Sort
Содержит справочную документацию по Sort методу. Provides reference documentation for the Sort method.
DataGridViewColumn.SortMode
Содержит справочную документацию по SortMode свойству. Provides reference documentation for the SortMode property.
DataGridViewColumnSortMode
Содержит справочную документацию по DataGridViewColumnSortMode перечислению. Provides reference documentation for the DataGridViewColumnSortMode enumeration.
Практическое руководство. Настройка сортировки данных элемента управления DataGridView в Windows Forms How to: Customize Sorting in the Windows Forms DataGridView Control
Элемент управления DataGridView обеспечивает автоматическую сортировку, но в определенных ситуациях может потребоваться настроить операции сортировки. 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). Кроме того, можно обработать событие SortCompare или вызвать перегрузку Sort(IComparer) метода Sort для обеспечения большей гибкости сортировки, например для сортировки нескольких столбцов. 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. Дополнительные сведения см. в разделе Установка режимов сортировки для столбцов элемента управления DataGridView в Windows Forms. For more information, see Column Sort Modes in the Windows Forms DataGridView Control.
Программная сортировка Programmatic Sorting
В примере кода ниже демонстрируется программная сортировка с использованием свойств SortOrder и SortedColumn для определения направления сортировки и свойства SortGlyphDirection для ручной установки глифа сортировки. 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. Перегрузка Sort(DataGridViewColumn,ListSortDirection) метода Sort используется для сортировки данных только в одном столбце. The Sort(DataGridViewColumn,ListSortDirection) overload of the Sort method is used to sort data only in a single column.
Пользовательская сортировка с помощью события SortCompare Custom Sorting Using the SortCompare Event
В примере кода ниже демонстрируется пользовательская сортировка с использованием обработчика событий SortCompare. The following code example demonstrates custom sorting using a SortCompare event handler. Выбранный столбец DataGridViewColumn сортируется, а при обнаружении в нем повторяющихся значений столбец ID используется для определения конечного порядка. The selected DataGridViewColumn is sorted and, if there are duplicate values in the column, the ID column is used to determine the final order.
Пользовательская сортировка с помощью интерфейса IComparer Custom Sorting Using the IComparer Interface
В примере кода ниже демонстрируется пользовательская сортировка с помощью перегрузки Sort(IComparer) метода Sort, которая принимает реализацию интерфейса IComparer для выполнения сортировки по нескольким столбцам. 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.
Компиляция кода Compiling the Code
Для этих примеров требуются: These examples require:
Фильтрация и сортировка данных в приложении Windows Forms Filter and sort data in a Windows Forms application
Данные фильтруются путем присвоения Filter свойству строкового выражения, возвращающего нужные записи. You filter data by setting the Filter property to a string expression that returns the desired records.
Данные сортируются путем присвоения Sort свойству имени столбца, по которому нужно выполнить сортировку; добавление DESC в сортировку в убывающем порядке или добавление ASC к сортировке по возрастанию. You sort data by setting the Sort property to the column name on which you want to sort; append DESC to sort in descending order, or append ASC to sort in ascending order.
Если приложение не использует BindingSource компоненты, можно фильтровать и сортировать данные с помощью DataView объектов. If your application does not use BindingSource components, you can filter and sort data by using DataView objects. Дополнительные сведения см. в разделе » представленияданных». For more information, see DataViews.
Фильтрация данных с помощью компонента BindingSource To filter data by using a BindingSource component
Задайте Filter для свойства выражение, которое требуется вернуть. Set the Filter property to the expression you want to return. Например, следующий код возвращает клиентов с CompanyName , который начинается с «B»: For example, the following code returns customers with a CompanyName that starts with «B»:
Сортировка данных с помощью компонента BindingSource To sort data by using a BindingSource component
Задайте Sort для свойства столбец, по которому необходимо выполнить сортировку. Set the Sort property to the column you want to sort on. Например, следующий код сортирует клиентов по CompanyName столбцу в убывающем порядке: For example, the following code sorts customers on the CompanyName column in descending order:
List Box. Sorted Свойство
Определение
Получает или задает значение, показывающее, упорядочены ли позиции ListBox по алфавиту. Gets or sets a value indicating whether the items in the ListBox are sorted alphabetically.
Значение свойства
Значение true , если значения элемента управления отсортированы по алфавиту, в обратном случае значение false . true if items in the control are sorted; otherwise, false . Значение по умолчанию — false . The default is false .
Примеры
В следующем примере кода показано, как с помощью GetSelected метода определить, какие элементы в ListBox выбраны, чтобы выбрать элементы, которые не выбраны, и отменить выбор выбранных элементов. The following code example demonstrates how to use the GetSelected method to determine which items in a ListBox are selected in order to select the items that are not selected and deselect the items that are selected. В этом примере также демонстрируется использование SelectionMode свойства для включения ListBox в для нескольких выбранных элементов и использования Sorted свойства для демонстрации автоматического упорядочения элементов ListBox . The example also demonstrates using the SelectionMode property to enable a ListBox to have more than one selected item and uses the Sorted property to demonstrate how to sort items in a ListBox automatically. В этом примере требуется ListBox , чтобы в listBox1 форму был добавлен объект с именем, а метод, InitializeMyListBox определенный в примере, вызывался из Load события формы. This example requires that a ListBox, named listBox1 , has been added to a form and that the InitializeMyListBox method defined in the example is called from the Load event of the form.
Комментарии
Используйте Sorted свойство для автоматической сортировки строк в алфавитном порядке в ListBox . Use the Sorted property to automatically sort strings alphabetically in a ListBox. При добавлении элементов в отсортированный ListBox список элементы перемещаются в соответствующее место в отсортированном списке. As items are added to a sorted ListBox, the items are moved to the appropriate location in the sorted list. При добавлении элементов в ListBox , более эффективно сортировать элементы сначала, а затем добавлять новые элементы. When adding items to a ListBox, it is more efficient to sort the items first and then add new items.
Объект ListBox со Sorted свойством, имеющим значение, true не должен быть привязан к данным с помощью DataSource Свойства. A ListBox with its Sorted set to true should not be bound to data using the DataSource property. Чтобы отобразить отсортированные данные в привязанном элементе ListBox , необходимо выполнить привязку к источнику данных, который поддерживает сортировку и предоставить источнику данных возможность сортировки. To display sorted data in a bound ListBox, you should bind to a data source that supports sorting and have the data source provide the sorting.
Установка режимов сортировки для столбцов элемента управления DataGridView в Windows Forms Column Sort Modes in the Windows Forms DataGridView Control
DataGridView столбцы имеют три режима сортировки. DataGridView columns have three sort modes. Режим сортировки для каждого столбца задается с помощью SortMode Свойства столбца, для которого можно задать одно из следующих DataGridViewColumnSortMode значений перечисления. 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 DataGridViewColumnSortMode value | Описание Description |
---|---|
Automatic | По умолчанию для столбцов текстового поля. Default for text box columns. Если для выделения не используются заголовки столбцов, при щелчке заголовка столбца автоматически сортируется DataGridView по этому столбцу и отображается глиф, указывающий порядок сортировки. 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. |
Может потребоваться изменить режим сортировки для столбца, который по умолчанию NotSortable имеет значение, если он содержит значения, которые могут быть осмысленно упорядочены. You might want to change the sort mode for a column that defaults to NotSortable if it contains values that can be meaningfully ordered. Например, если имеется столбец базы данных, содержащий числа, представляющие состояния элементов, эти числа можно отобразить в виде соответствующих значков путем привязки столбца Image к столбцу базы данных. 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. Затем числовые значения ячейки можно изменить на отображаемые значения изображения в обработчике DataGridView.CellFormatting события. You can then change the numerical cell values into image display values in a handler for the DataGridView.CellFormatting event. В этом случае, если задать SortMode для свойства значение, Automatic пользователи смогут сортировать столбец. 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.
Можно выполнить сортировку DataGridView программными средствами по значениям в любом столбце или в нескольких столбцах независимо от SortMode параметров. 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. Предоставление собственного пользовательского интерфейса сортировки полезно, например, при установке DataGridView режима выделения для включения выбора заголовка столбца. Providing your own sorting UI is useful, for example, when you set the DataGridView selection mode to enable column header selection. В этом случае, несмотря на то, что заголовки столбцов нельзя использовать для сортировки, все равно требуется, чтобы в заголовках отображался соответствующий глиф сортировки, поэтому необходимо задать SortMode для свойства значение Programmatic . 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. Для этих столбцов необходимо самостоятельно отобразить глиф, задав DataGridViewColumnHeaderCell.SortGlyphDirection свойство. 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. Например, при сортировке DataGridView по нескольким столбцам может потребоваться отобразить несколько глифов сортировки или без глифа сортировки. For example, if you sort the DataGridView by multiple columns, you might want to display multiple sorting glyphs or no sorting glyph.
Хотя можно программно сортировать DataGridView по любому столбцу, некоторые столбцы, например столбцы кнопок, могут не содержать значений, которые могут быть осмысленно упорядочены. 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. Для этих столбцов SortMode параметр свойства NotSortable указывает, что он никогда не будет использоваться для сортировки, поэтому нет необходимости зарезервировать место в заголовке для глифа сортировки. 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.
При DataGridView сортировке можно определить как столбец сортировки, так и порядок сортировки, проверив значения SortedColumn SortOrder свойств и. 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.
При DataGridView сортировке элемента управления, содержащего как связанные, так и несвязанные столбцы, значения в непривязанных столбцах не могут поддерживаться автоматически. When a DataGridView control containing both bound and unbound columns is sorted, the values in the unbound columns cannot be maintained automatically. Чтобы сохранить эти значения, необходимо реализовать виртуальный режим, задав VirtualMode свойству значение true и обрабатывающее CellValueNeeded события и CellValuePushed . To maintain these values, you must implement virtual mode by setting the VirtualMode property to true and handling the CellValueNeeded and CellValuePushed events. Дополнительные сведения см. в разделе инструкции. Реализация виртуального режима в элементе управления Windows Forms DataGridView. 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
Можно выполнить сортировку DataGridView программным путем, вызвав его Sort метод. You can sort a DataGridView programmatically by calling its Sort method.
Sort(DataGridViewColumn,ListSortDirection) Перегрузка Sort метода принимает в DataGridViewColumn ListSortDirection качестве параметров значение и перечисления. 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. При вызове этой перегрузки и передаче столбца со SortMode значением свойства DataGridViewColumnSortMode.Automatic , SortedColumn SortOrder Свойства и задаются автоматически, а соответствующий глиф сортировки отображается в заголовке столбца. 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.
Если DataGridView элемент управления привязан к внешнему источнику данных путем установки DataSource свойства, Sort(DataGridViewColumn,ListSortDirection) перегрузка метода не работает для непривязанных столбцов. 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. Кроме того, если VirtualMode свойство равно true , можно вызвать эту перегрузку только для связанных столбцов. Additionally, when the VirtualMode property is true , you can call this overload only for bound columns. Чтобы определить, привязан ли столбец к данным, проверьте IsDataBound значение свойства. To determine whether a column is data-bound, check the IsDataBound property value. Сортировка непривязанных столбцов в связанном режиме не поддерживается. Sorting unbound columns in bound mode is not supported.
Пользовательская сортировка Custom Sorting
Можно настроить с DataGridView помощью Sort(IComparer) перегрузки Sort метода или путем обработки SortCompare события. You can customize DataGridView by using the Sort(IComparer) overload of the Sort method or by handling the SortCompare event.
Sort(IComparer) Перегрузка метода принимает экземпляр класса, который реализует IComparer интерфейс в качестве параметра. 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. Эту перегрузку можно вызвать в обработчике для ColumnHeaderMouseClick события, если заголовки столбцов не используются для выбора. You can call this overload in a handler for the ColumnHeaderMouseClick event if you do not use column headers for selection.
Sort(IComparer) Перегрузка метода работает, только если DataGridView элемент управления не привязан к внешнему источнику данных, а VirtualMode свойство имеет значение false . 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.
Чтобы использовать Sort(IComparer) перегрузку метода, необходимо создать собственный класс, реализующий IComparer интерфейс. To use the Sort(IComparer) method overload, you must create your own class that implements the IComparer interface. Этот интерфейс требует, чтобы ваш класс реализовал IComparer.Compare метод, который DataGridView передает объекты в DataGridViewRow качестве входных данных при Sort(IComparer) вызове перегрузки метода. 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.
Sort(IComparer) Перегрузка метода не задает SortedColumn SortOrder Свойства и, поэтому необходимо всегда устанавливать DataGridViewColumnHeaderCell.SortGlyphDirection свойство для вывода глифа сортировки. 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.
В качестве альтернативы Sort(IComparer) перегрузке метода можно предоставить пользовательскую сортировку, реализовав обработчик для SortCompare события. As an alternative to the Sort(IComparer) method overload, you can provide custom sorting by implementing a handler for the SortCompare event. Это событие возникает, когда пользователи щелкают заголовки столбцов, настроенных для автоматической сортировки, или при вызове Sort(DataGridViewColumn,ListSortDirection) перегрузки Sort метода. 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.
SortCompareСобытие не происходит, если DataSource свойство задано или если VirtualMode свойство имеет значение true . The SortCompare event does not occur when the DataSource property is set or when the VirtualMode property value is true .