如何:使用 Windows 窗体 BindingSource 组件对 ADO.NET 数据进行排序和筛选

可以通过SortFilter属性公开BindingSource控件的排序和筛选功能。 当基础数据源是一个 IBindingList时,可以应用简单的排序,当数据源是一个 IBindingListView时,可以应用筛选和高级排序。 该 Sort 属性需要标准 ADO.NET 语法:一个表示数据源中某数据列名称的字符串,后接 ASCDESC 指示列表应按升序或降序排序。 可以通过用逗号分隔符分隔每列来设置高级排序或多列排序。 该 Filter 属性采用字符串表达式。

注释

在连接字符串中存储敏感信息(如密码)可能会影响应用程序的安全性。 使用 Windows 身份验证(也称为集成安全性)是控制对数据库的访问的更安全方法。 有关详细信息,请参阅保护连接信息

使用 BindingSource 筛选数据

  • Filter 属性设置为所需的表达式。

    在下面的代码示例中,表达式是一个列名,后跟该列所需的值。

BindingSource1.Filter = "ContactTitle='Owner'";
BindingSource1.Filter = "ContactTitle='Owner'"

使用 BindingSource 对数据进行排序

  1. Sort属性设置为要使用的列名,然后通过ASCDESC指示升序或降序。

  2. 用逗号分隔多个列。

BindingSource1.Sort = "Country DESC, Address ASC";
BindingSource1.Sort = "Country DESC, Address ASC"

示例:

下面的代码示例将数据从 Northwind 示例数据库的 Customers 表加载到控件 DataGridView 中,并筛选和排序显示的数据。

private void InitializeSortedFilteredBindingSource()
{
    // Create the connection string, data adapter and data table.
    SqlConnection connectionString =
         new SqlConnection("Initial Catalog=Northwind;" +
         "Data Source=localhost;Integrated Security=SSPI;");
    SqlDataAdapter customersTableAdapter =
        new SqlDataAdapter("Select * from Customers", connectionString);
    DataTable customerTable = new DataTable();

    // Fill the adapter with the contents of the customer table.
    customersTableAdapter.Fill(customerTable);

    // Set data source for BindingSource1.
    BindingSource1.DataSource = customerTable;

    // Filter the items to show contacts who are owners.
    BindingSource1.Filter = "ContactTitle='Owner'";

    // Sort the items on the company name in descending order.
    BindingSource1.Sort = "Country DESC, Address ASC";

    // Set the data source for dataGridView1 to BindingSource1.
    dataGridView1.DataSource = BindingSource1;
}
Private Sub InitializeSortedFilteredBindingSource()

    ' Create the connection string, data adapter and data table.
    Dim connectionString As New SqlConnection("Initial Catalog=Northwind;" & _
        "Data Source=localhost;Integrated Security=SSPI;")
    Dim customersTableAdapter As New SqlDataAdapter("Select * from Customers", _
        connectionString)
    Dim customerTable As New DataTable()

    ' Fill the adapter with the contents of the customer table.
    customersTableAdapter.Fill(customerTable)

    ' Set data source for BindingSource1.
    BindingSource1.DataSource = customerTable

    ' Filter the items to show contacts who are owners.
    BindingSource1.Filter = "ContactTitle='Owner'"
    ' Sort the items on the company name in descending order.
    BindingSource1.Sort = "Country DESC, Address ASC"

    ' Set the data source for dataGridView1 to BindingSource1.
    dataGridView1.DataSource = BindingSource1

   
End Sub

编译代码

若要运行此示例,请将代码粘贴到包含 BindingSource 命名 BindingSource1DataGridView 命名 dataGridView1的窗体中。 处理 Load 表单的事件,并在加载事件处理程序方法中调用 InitializeSortedFilteredBindingSource

另请参阅