BindingSource.Sort Свойство

Определение

Возвращает или задает имена столбцов, используемые для сортировки, и порядок сортировки для просмотра строк в источнике данных.

public:
 property System::String ^ Sort { System::String ^ get(); void set(System::String ^ value); };
public string Sort { get; set; }
public string? Sort { get; set; }
member this.Sort : string with get, set
Public Property Sort As String

Значение свойства

Строка (с учетом регистра символов), содержащая имя столбца, за которым следует либо "ASC" (сортировка по возрастанию), либо "DESC" (сортировка по убыванию). Значение по умолчанию — null.

Примеры

В следующем примере показано, как использовать Sort свойство для выполнения базовой сортировки с помощью DataView. Чтобы выполнить этот пример, вставьте код в Форму Windows Form и вызовите PopulateDataViewAndSort из конструктора формы или Load метода обработки событий. Форма должна импортировать System.Xml пространства имен и System.IO .

private void PopulateDataViewAndSort()
{
    DataSet set1 = new DataSet();

    // Some xml data to populate the DataSet with.
    string musicXml =
        "<?xml version='1.0' encoding='UTF-8'?>" +
        "<music>" +
        "<recording><artist>Coldplay</artist><cd>X&Y</cd></recording>" +
        "<recording><artist>Dave Matthews</artist><cd>Under the Table and Dreaming</cd></recording>" +
        "<recording><artist>Dave Matthews</artist><cd>Live at Red Rocks</cd></recording>" +
        "<recording><artist>Natalie Merchant</artist><cd>Tigerlily</cd></recording>" +
        "<recording><artist>U2</artist><cd>How to Dismantle an Atomic Bomb</cd></recording>" +
        "</music>";

    // Read the xml.
    StringReader reader = new StringReader(musicXml);
    set1.ReadXml(reader);

    // Get a DataView of the table contained in the dataset.
    DataTableCollection tables = set1.Tables;
    DataView view1 = new DataView(tables[0]);

    // Create a DataGridView control and add it to the form.
    DataGridView datagridview1 = new DataGridView();
    datagridview1.AutoGenerateColumns = true;
    this.Controls.Add(datagridview1);

    // Create a BindingSource and set its DataSource property to
    // the DataView.
    BindingSource source1 = new BindingSource();
    source1.DataSource = view1;

    // Set the data source for the DataGridView.
    datagridview1.DataSource = source1;

    source1.Sort = "cd";
}
Private Sub PopulateDataViewAndSort() 
    Dim set1 As New DataSet()
    
    ' Some xml data to populate the DataSet with.
    Dim musicXml As String = "<?xml version='1.0' encoding='UTF-8'?>" & _
        "<music>" & _
        "<recording><artist>Coldplay</artist><cd>X&Y</cd></recording>" & _
        "<recording><artist>Dave Matthews</artist><cd>Under the Table and Dreaming</cd></recording>" & _
        "<recording><artist>Dave Matthews</artist><cd>Live at Red Rocks</cd></recording>" & _
        "<recording><artist>Natalie Merchant</artist><cd>Tigerlily</cd></recording>" & _
        "<recording><artist>U2</artist><cd>How to Dismantle an Atomic Bomb</cd></recording>" & _
         "</music>"
    
    ' Read the xml.
    Dim reader As New StringReader(musicXml)
    set1.ReadXml(reader)
    
    ' Get a DataView of the table contained in the dataset.
    Dim tables As DataTableCollection = set1.Tables
    Dim view1 As New DataView(tables(0))
    
    ' Create a DataGridView control and add it to the form.
    Dim datagridview1 As New DataGridView()
    datagridview1.AutoGenerateColumns = True
    Me.Controls.Add(datagridview1)
    
    ' Create a BindingSource and set its DataSource property to
    ' the DataView.
    Dim source1 As New BindingSource()
    source1.DataSource = view1
    
    ' Set the data source for the DataGridView.
    datagridview1.DataSource = source1
    
    source1.Sort = "cd"

End Sub

В следующем примере показано, как использовать Sort свойство для выполнения расширенной сортировки с помощью DataView. Чтобы выполнить этот пример, вставьте код в Форму Windows Form и вызовите PopulateDataViewAndAdvancedSort из конструктора формы или Load метода обработки событий. Форма должна импортировать System.Xml пространства имен и System.IO .

private void PopulateDataViewAndAdvancedSort()
{
    DataSet set1 = new DataSet();

    // Some xml data to populate the DataSet with.
    string musicXml =
        "<?xml version='1.0' encoding='UTF-8'?>" +
        "<music>" +
        "<recording><artist>Dave Matthews</artist><cd>Under the Table and Dreaming</cd></recording>" +
        "<recording><artist>Coldplay</artist><cd>X&Y</cd></recording>" +
        "<recording><artist>Dave Matthews</artist><cd>Live at Red Rocks</cd></recording>" +
        "<recording><artist>U2</artist><cd>Joshua Tree</cd></recording>" +
        "<recording><artist>U2</artist><cd>How to Dismantle an Atomic Bomb</cd></recording>" +
        "<recording><artist>Natalie Merchant</artist><cd>Tigerlily</cd></recording>" +
        "</music>";

    // Read the xml.
    StringReader reader = new StringReader(musicXml);
    set1.ReadXml(reader);

    // Get a DataView of the table contained in the dataset.
    DataTableCollection tables = set1.Tables;
    DataView view1 = new DataView(tables[0]);

    // Create a DataGridView control and add it to the form.
    DataGridView datagridview1 = new DataGridView();
    datagridview1.AutoGenerateColumns = true;
    this.Controls.Add(datagridview1);

    // Create a BindingSource and set its DataSource property to
    // the DataView.
    BindingSource source1 = new BindingSource();
    source1.DataSource = view1;

    // Set the data source for the DataGridView.
    datagridview1.DataSource = source1;

    source1.Sort = "artist ASC, cd ASC";
}
Private Sub PopulateDataViewAndAdvancedSort() 
    Dim set1 As New DataSet()
    
    ' Some xml data to populate the DataSet with.
    Dim musicXml As String = "<?xml version='1.0' encoding='UTF-8'?>" & _
        "<music>" & _
        "<recording><artist>Dave Matthews</artist><cd>Under the Table and Dreaming</cd></recording>" & _
        "<recording><artist>Coldplay</artist><cd>X&Y</cd></recording>" & _
        "<recording><artist>Dave Matthews</artist><cd>Live at Red Rocks</cd></recording>" & _
        "<recording><artist>U2</artist><cd>Joshua Tree</cd></recording>" & _
        "<recording><artist>U2</artist><cd>How to Dismantle an Atomic Bomb</cd></recording>" & _
        "<recording><artist>Natalie Merchant</artist><cd>Tigerlily</cd></recording>" & _
        "</music>"
    
    ' Read the xml.
    Dim reader As New StringReader(musicXml)
    set1.ReadXml(reader)
    
    ' Get a DataView of the table contained in the dataset.
    Dim tables As DataTableCollection = set1.Tables
    Dim view1 As New DataView(tables(0))
    
    ' Create a DataGridView control and add it to the form.
    Dim datagridview1 As New DataGridView()
    datagridview1.AutoGenerateColumns = True
    Me.Controls.Add(datagridview1)
    
    ' Create a BindingSource and set its DataSource property to
    ' the DataView.
    Dim source1 As New BindingSource()
    source1.DataSource = view1
    
    ' Set the data source for the DataGridView.
    datagridview1.DataSource = source1
    
    source1.Sort = "artist ASC, cd ASC"

Комментарии

Свойство Sort — это строка с учетом регистра, указывающая имена столбцов, используемых для сортировки строк, а также направление сортировки. Столбцы сортируются по возрастанию по умолчанию. Несколько столбцов можно разделить запятыми, например "State, ZipCode DESC".

Для поддержки сортировки базовый список должен реализовывать IBindingList интерфейсы или IBindingListView . Эту возможность можно запросить с помощью SupportsSorting свойства . Сортировка по нескольким столбцам доступна, SupportsAdvancedSorting если свойство имеет значение true.

Sort Задание свойства изменит внутренний список в зависимости от его типа:

Свойства сортировки внутреннего списка изменяются, только если строка сортировки не nullимеет значение . Метод get доступа для этого свойства не получает значение сортировки внутреннего списка, а возвращает set значение метода доступа. Значение Sort свойства будет сохраняться при изменении источника данных.

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

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